JPA CriteriaBuilder how to create join + like query

こ雲淡風輕ζ 提交于 2019-12-11 05:16:58

问题


I have a SQL query:

   SELECT s.*, p.name, p.code 
     FROM `stock` s 
LEFT JOIN product p ON s.product_id = p.id 
    WHERE p.name LIKE "%q%"

And I need to create the query using criteriabuilder

I started so:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<Stock> stock = cq.from(Stock.class);

Path<String> path = stock.get(filter.getKey());//i have error here
String likeValue = wildCard + value + wildCard;
Predicate filterCondition = cb.conjunction();
filterCondition = cb.and(filterCondition, cb.like(path, likeValue));

Please help, how to do it better?


回答1:


  1. the selection is unclear. In SQL you select s.*, p.name, p.code, but in criteria you expect a Long?

  2. your LEFT JOIN has not to be LEFT.

  3. in criteria you've no join at all.

  4. you should use metamodel, as a general advice.

I think you want all Stocks which contain at least one Product with name like %value%.

If my assumption is right:

CriteriaBuilder cb = em.getCriteriaBuilder();

CriteriaQuery<Stock> cq = cb.createQuery(Stock.class);

Root<Stock> stock = cq.from(Stock.class);
Join<Stock, Product> product = stock.join(Stock_.products);

cq.select(stock);
cq.distinct(true);
cq.where(cb.like(product.get(Product_.name), "%" + value + "%");

return em.createQuery(cq).getResultList();


来源:https://stackoverflow.com/questions/41647477/jpa-criteriabuilder-how-to-create-join-like-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!