JPA Dynamic Query splicing

In use Spring JPA offers only a simple CRUD, if you encounter a complex situation requires us to dynamically build a query. Here we look at how to construct queries using CriteriaBuilder.
Core code:

CriteriaBuilder = entityManager.getCriteriaBuilder CriteriaBuilder ();
a CriteriaQuery <Long> Query = criteriaBuilder.createQuery (Long.class);
Root <the Order> = query.from the root (Order.class);
query.select (criteriaBuilder.count (root.get ( "ID")));
the Predicate the predicateA = criteriaBuilder.equal (root.get ( "ID"),. 1);
query.where (the predicateA);
Long singleResult entityManager.createQuery = (Query) .getSingleResult ();

call entityManager .getCriteriaBuilder () to get CriteriaBuilder. CriteriaBuilder be used to create CriteriaQuery, CriteriaUpdate and CriteriaDelete. In addition to a similar count, max, etc. is also a function of CriteriaBuilder to create. Wherein Entitymanager @PersistenceContext annotations can be used for injection.
Call criteriaBuilder.createQuery to create CriteriaQuery. Wherein the parameter is createQuery Query return type.
Call query.from (Order.class). Order parameter table corresponding to the entity class, query.from sql statement from the similar, it is equivalent to performing the method from the order sql.
Call query.select create the mapping. query.select (criteriaBuilder.count (root.get ( "id "))) is equivalent to select count (id). If you do query.select (root) is equivalent to select *.
Use CriteriaBuilder construct the query conditions Predicate, the predicate is in the condition where the back of the clause.
The Predicate in query.where in.
Finally, execute a query to obtain data.
----------------
Disclaimer: This article is CSDN blogger "the way the setting sun," the original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source and this link statement.
Original link: https: //blog.csdn.net/zhaoruda/article/details/80157975

Guess you like

Origin www.cnblogs.com/fengli9998/p/11880324.html