java - 来自 Controller 的 Spring Boot 查询

标签 java spring-boot jpa spring-data-jpa

我有这样的User类:

@Data
@Entity
public class User {
@Id @GeneratedValue Long userID;
String eMail;
String passwordHash;
}

我有这样的数据:

[{"userID":1,"passwordHash":"asdasd","email":"admin@admin.com"},
{"userID":2,"passwordHash":"12345","email":"admin1asdasd@admin.com"}]

我的 Controller 类中有两种方法,一种是获取单个用户:

@GetMapping("/user/{id}")
User one(@PathVariable Long id) {
    return repository.findById(id)
            .orElseThrow(() -> new UserNotFoundException(id));
}

检索所有用户的其他方法:

@GetMapping("/user")
List<User> all() {
    return repository.findAll();
}

在我的浏览器中,访问这个地址 - http://localhost:8080/user ,我可以看到这些数据。如果我转到http://localhost:8080/user/id我可以获得一个特定的值。

现在我的问题是如何访问像http://localhost:8080/user/email/passwordHash这样的数据?我很确定这是不可能的,因为我没有以这种方式存储数据。

由于我的主要目标是验证登录,因此我已经在存储库界面中编写了一个@Query。这是:

public interface UserRepository extends JpaRepository<User, Long> {

@Query("select u from User u where u.eMail = ?1 and u.passwordHash = ?2")
List<User> listByLoginCredential(String emailAddress,String passwordHash);
 }

谁能告诉我该怎么做,使用这个接口(interface)的这个方法吗?

最佳答案

我认为你可以通过在 Controller 类中添加以下方法来实现你想要的:

@GetMapping("/user/{emailAddress}/{passwordHash}")
List<User> byMailAndPassword(@PathVariable String emailAddress, @PathVariable String passwordHash) {
    return repository.listByLoginCredential(emailAddress, passwordHash)
}

另一方面,您说您的主要目标是验证登录,因此看起来您正在进行身份验证。如果你有时间,你应该考虑使用 spring security https://spring.io/guides/gs/securing-web/#initial 来做这件事。

关于java - 来自 Controller 的 Spring Boot 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57587172/

相关文章:

java - ProgressBar 不会改变它在 Java 中的值

java - 数据库android从表中选择

spring-boot - Spring Cloud Config 不解密配置服务器密码

java - JTree:不会重新显示新模型

用于自动回归 (AR)、ARIMA、时间序列分析的 Java API

java - 使用 Gradle 和 Docker 部署 Spring Boot/PostgreSQL 项目

java - 无法访问 spring boot 执行器的/beans

java - merge如何避免LazyInitException?

jpa - 如何通过 EntityManager 从 InputStream 更新 BLOB?

java - JPA只指RDBMS吗