簡體   English   中英

使用 JpaRepository 創建類似於 findById 的 findByEmail 方法

[英]Use JpaRepository to create findByEmail method which is similer to findById

我有一個帶有以下 DAO 的 Spring 引導項目:

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() 方法應該使用 email 地址查詢用戶以獲取 ID,然后用它調用 findById。 我怎么做?

我認為您可以創建一個方法

List<User> findByEmail(String emailAddress);

在你的 DAO 中。

看看這個頁面

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

在“查詢創建”部分中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM