How can I create a Predicate from a HQL query?

邮差的信 提交于 2019-12-25 08:49:23

问题


I have this repository:

@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();

}

But I want to change the @Query by a custom Spring Data Specification, in order to call it like:

repository.findAll(new Allowed());

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) {
      //??
    }
}

How can I convert the query above to a Predicate? How can I perform the join with UserRole entity?


回答1:


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;
            }
        };
    }
}

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.



来源:https://stackoverflow.com/questions/41479366/how-can-i-create-a-predicate-from-a-hql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!