Héctor
Héctor

Reputation: 26034

How can I create a Predicate from a HQL query?

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?

Upvotes: 1

Views: 1722

Answers (1)

Avinash
Avinash

Reputation: 4279

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.

Upvotes: 1

Related Questions