如何从HQL查询创建谓词? [英] How can I create a Predicate from a HQL query?
问题描述
我有这个存储库:
@Repository
public interface UserRepository extends
JpaRepository<User, String>,
JpaSpecificationExecutor<User> {
@Query("select u from User u, UserRole ur " +
"where u.dep = ur.dep " +
"and u.allowed = 1")
List<User> getAllowed();
}
但是我想通过自定义Spring Data Specification
更改@Query
,以便像这样调用它:
But I want to change the @Query
by a custom Spring Data Specification
, in order to call it like:
repository.findAll(new Allowed());
所以我已经将extends JpSpecificationExecutor<User>
添加到我的存储库中,现在我正在尝试创建Specification
实现:
So I have added extends JpSpecificationExecutor<User>
to my repository and now I'm trying to create the Specification
implementation:
public class Allowed implements Specification<User> {
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
//??
}
}
如何将上面的查询转换为谓词?如何使用UserRole
实体执行联接?
How can I convert the query above to a Predicate? How can I perform the join with UserRole
entity?
推荐答案
创建一个创建并返回规范的类,其好处是该类可以根据各种情况返回单独的规范.
Create a class which creates and returns specification, its benefit is that this class can return separate specifications based on various situations.
@Component
public class UserSpecification {
public Specification<User> getAllowedUserSpecification() {
return new Specification<User>() {
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Predicate predicate = cb.equal(root.get("allowed"), "1");
return predicate;
}
};
}
}
然后在Service类中只是将上面的类自动接线并像下面那样使用
Then in Service class just autowire the above class and use it like below
repo.findAll(userSpecification.getAllowedUserSpecification());
规范中不需要用户和用户角色的联接,因为在创建实体类时必须设置关系.
The join of User and UserRole is not required in specification because you have to set relationship while creating the entity class.
这篇关于如何从HQL查询创建谓词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!