Search code examples
javahibernatehibernate-criteria

Equivalent criteria query for named query


My named query looks like this, thanks to here.

@NamedQuery(
name="Cat.favourites", 
query="select c 
      from Usercat as uc 
      inner join uc.cat as c 
      where uc.isFavourtie = true 
      and uc.user = :user")

And the call to implement looks like this :

Session session = sessionFactory.getCurrentSession();
Query query = session.getNamedQuery("Cat.favourites");
query.setEntity("user", myCurrentUser);
return query.list();

What would be the equivalent criteria query that returns a list of cats ?


Solution

  • With JPA 2.0 Criteria: (This is one of the many ways you can achieve this using JPA 2.0 Criteria api)

    final CriteriaQuery<Cat> cq = getCriteriaBuilder().createQuery(Cat.class);
    final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    
    final Root<Usercat> uc= cq.from(Usercat.class);
    
    cq.select(uc.get("cat");
    
    Predicate p = cb.equal(uc.get("favourtie", true);
    p = cb.and(p, cb.equal(uc.get("user"), user));
    cq.where(p);
    
    final TypedQuery<Cat> typedQuery = entityManager.createQuery(cq);
    return typedQuery.getResultList();