问题
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:
the selection is unclear. In SQL you select
s.*, p.name, p.code
, but in criteria you expect aLong
?your
LEFT JOIN
has not to beLEFT
.in criteria you've no join at all.
you should use metamodel, as a general advice.
I think you want all Stock
s 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