[英]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 中。
看看這個頁面
在“查詢創建”部分中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.