How to write this query using JPA Criteria query?

后端 未结 2 628
攒了一身酷
攒了一身酷 2021-02-04 14:39

Can anyone help me to get the JPA criteria query for the JPA query mentioned below.

SELECT p,l FROM Person p 
LEFT JOIN Language l ON (p.language = l.language an         


        
2条回答
  •  灰色年华
    2021-02-04 15:33

    Assuming that Person has a relation to Language here's what you would do in older Hibernate:

    Criteria criteria = entityManager.createCriteria(Person.class);
    Criteria languageCriteria = criteria.createCriteria("language");
    
    languageCriteria.add(Restrictions.like("locale", locale));
    
    criteria.add(Restrictions.like("name", name));
    criteria.add(Restrictions.between("time", startDate, endDate));
    
    criteria.addOrder(Order.asc("name"));
    

    and my first try at JPA 2.0:

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery criteria = builder.createCriteria(Person.class);
    Root pRoot = criteria.from(Person.class);
    Join langJoin = criteria.join("language", JoinType.LEFT);
    
    Predicate conjunction = builder.conjunction();
    
    criteria.where(builder.and(
        builder.like(langJoin.get(Language_.locale), locale),
        builder.like(pRoot.get(Person_.name), name),
        builder.between(pRoot.get(Person_.time), startDate, endDate));
    
    criteria.orderBy(builder.asc(pRoot.get(Person_.name)));
    

    Please let me know if that works for you.

    Edit: Updated query to use only one where call.

提交回复
热议问题