使用JpaRepository创建类似于findById的findByEmail方法



我有一个Spring Boot项目,包含以下DAO:

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((方法应该用电子邮件地址查询User以获得ID,然后用它调用findById。我该怎么做?

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

List<User> findByEmail(String emailAddress);

在您的DAO中。

看看这个页面的

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

在部分中:";查询创建"。

相关内容

最新更新