1

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?

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
Héctor
  • 24,444
  • 35
  • 132
  • 243

1 Answers1

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.

Avinash
  • 4,115
  • 2
  • 22
  • 41