【发布时间】: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