【问题标题】:Use JpaRepository to create findByEmail method which is similer to findById使用 JpaRepository 创建类似于 findById 的 findByEmail 方法
【发布时间】:2020-12-03 19:59:57
【问题描述】:

我有一个带有以下 DAO 的 Spring Boot 项目:

public interface UserRepository extends JpaRepository<User, Integer> {
    
    // method to sort by last name
    public List<User> findAllByOrderByLastNameAsc();

}

它还有一个带有以下 findById() 的服务:

@Override
public User findById(int theId) {
    Optional<User> result = userRepository.findById(theId);
        
    User theUser = null;
    if(result.isPresent()) {
        theUser = result.get();
    }
    else {
        // we didn't find the user
        throw new RuntimeException("Did not find userId: " + theId);
    }
    return theUser;
}

我想创建一个类似的 findByEmail()。以下将不起作用,因为 JpaRepository 没有 findByEmail 方法:

@Override
public User findByEmail(String theEmail) {
        
    Optional<User> result = userRepository.findByEmail(theEmail);
    User theUser = null;
    if(result.isPresent()) {
        theUser = result.get();
    }
    else {
        // we didn't find the user
        throw new RuntimeException("Did not find userId: " + theUser);
    }
    return theUser;
}

我认为我的 findByEmail() 方法应该使用电子邮件地址查询用户以获取 ID,然后使用它调用 findById。我该怎么做?

【问题讨论】:

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


    【解决方案1】:

    我认为你可以创建一个方法

    List<User> findByEmail(String emailAddress);
    

    在你的 DAO 中。

    看看这个页面

    (https://docs.spring.io/spring-data/jpa/docs/1.5.0.RELEASE/reference/html/jpa.repositories.html)

    在“查询创建”部分中。

    【讨论】:

    • 好的,谢谢。我试过了。我看到了UsernameNotFoundException。当我运行调试器时,一切都正确。我看不到正在执行的确切查询。有什么办法可以看到吗?
    • 不知道有没有办法查看执行的查询。但是在我的答案中附加的链接中,在查询创建部分中,第一个示例演示了 findByEmailAddress&Lastname 方法如何转换为查询。对于 UsernameNotFoundException 的问题,请提出新的答案,以便社区可以帮助您。
    猜你喜欢
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    • 2021-01-03
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多