在JpaRepository中,如果一个参数对于多个查询方法是通用的,那么如何在Repository和Service中尽


public interface UserRepo extends JpaRepository<User, Long> {
public List<User> findById(long id);
public List<User> findByEmail(String email);
public List<User> findByEmailAndCode(String email, Code code);
public List<User> findByEmailAndClassType(String email, ClassType code);
}
public class UserService {
@Autowired
UserRepo userRepo;
public List<user> fetchByClassType(ClassType ct) {
return userRepo.findByEmailAndClassType("email", ct);
}
}

这里的电子邮件需要提取一次如何避免它在数据库或控制器中的任何其他解决方案上花费很多时间,它需要在每个请求映射中一次又一次地给出。。。建议

您可以使用规范,而不是创建一堆类似的存储库方法。

请参阅此处的文档:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#specifications

您必须扩展JpaSecificationExecution:

public interface CustomerRepository extends CrudRepository<Customer, Long>, JpaSpecificationExecutor {
...
}

然后,您将获得一个接受Specification的findAll((方法。

创建一个规范,如:

public static Specification<Customer> isLongTermCustomer() {
return new Specification<Customer>() {
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query,
CriteriaBuilder builder) {
LocalDate date = new LocalDate().minusYears(2);
return builder.lessThan(root.get(_Customer.createdAt), date);
}
};
}

或者,如果您不喜欢JPA Criteria API,也可以使用QueryDSL

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.extensions.querydsl

最新更新