i'm trying to make a method in CrudRepository that will be able to give me a user with a JobType like one of these in my List of JobTypes. It should be something like aselect * from User where JobType like '%oneOfThejobTypesInMyList%';
Im trying the following but it wont work:
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
List<User> findByJobTypeLikeIn(List<String> jobType);
}
Can anybody help me with this?
To achieve like
with in
you have to use many like
with or
. You can do it with Criteria
without Repository
, for example:
@Autowired
EntityManager em;
private List<User> findByLikeIn(String columnName, List<String> values) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> cq = cb.createQuery(User.class);
Root<User> users = cq.from(User.class);
values.stream()
.map(v -> cb.like(users.get(columnName), "%" + v + "%"))
.reduce(cb::or)
.ifPresent(cq::where);
TypedQuery<User> query = em.createQuery(cq);
return query.getResultList();
}
And then use it:
List<String> jobType = Arrays.asList("aa", "dap");
List<User> resultList = findByLikeIn("jobType", jobType);
It should create something like that:
select u from User u where u.jobType like '%jobType1%' or u.jobType like '%jobType2%';
Or above code you can apply in specification :
public interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {
static Specification<User> containing(String columnName, List<String> values) {
return (root, query, builder) -> values.stream()
.map(v -> builder.like(root.get(columnName), "%" + v + "%"))
.reduce(builder::or)
.orElseGet(builder::conjunction);
}
and using it like this:
List<String> jobType = Arrays.asList("aa", "dap");
List<User> resultList = userRepository.findAll(UserRepository.containing("jobType", jobType))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.