Home Reversed "in" list clause JPA criteria in Hibernate
Reply: 0

Reversed "in" list clause JPA criteria in Hibernate

user2144
1#
user2144 Published in May 21, 2018, 11:00 am

I develop my project web application and I wanted to change searching profiles feature to use JPA Criteria. My idea is to ommit these searching criteria, which fields in html form were left blank. The difficult part is to write Predicate with String List of interests.

public List<Profile> searchProfiles(String sex, String city, List<String> interests) {   

    List<String> emptyInterests = new ArrayList<>(); emptyInterests.add(""); 
    Session session =  this.sessionFactory.getCurrentSession(); 
    CriteriaBuilder builder = session.getCriteriaBuilder();
    CriteriaQuery<Profile> criteriaQuery = builder.createQuery(Profile.class);  
    Root<Profile> root = criteriaQuery.from(Profile.class);

    List<Predicate> predicates = new ArrayList<>();

    if(!"".equals(sex)) {
        predicates.add(builder.equal(root.get("sex"), sex ));
    }

    if(!"".equals(city)) {
        predicates.add(builder.equal(root.get("city"), city ));             
    }

    if(!emptyInterests.equals(interests)) {
        // REASON OF ASKING THIS QUESTION 
    }

    criteriaQuery.select(root).where(predicates.toArray(new Predicate[]{}));

    return session.createQuery(criteriaQuery).list();
}

In the last "if" block I want to add Predicate which will means more or less "add Profile to results list if its String list of interests (Profile class field) contains all elements from method argument "interests" ". This condition in normal list filtering it would look like:

for(Profile profile : profiles) {
    if(profile.getInterests().contains(interests))
        results.add(profile);
}

Edit:
Following code causes ClassCastException: java.base/java.lang.String cannot be cast to java.base/java.util.List, in the return line.

    if(!emptyInterests.equals(interests))
    {
        Expression<String> interestsExpression = root.get("interests");
        Predicate interestsPredicate = interestsExpression.in(interests);
        predicates.add(interestsPredicate);   
    }
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.314581 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO