Criteria Query to retrieve data from DB using specification and predicate

931 views Asked by At

I have two tables (user, vehicles) and i want to write criteria query to retrieve data from db using criteria query specification and predicate to both Join Tables.

select ur.id, count (ur.vehicle_FK) from user so 
inner join VEHICLE vhe on vhe.user_id_FK = ur."ID"
group by ur.id, vhe.user_id_FK;

How to implement it using criteria query ??

2

There are 2 answers

0
SinisaT90 On

Try something like this :

Criteria criteria = session.createCriteria(User.class, "user");
criteria.createAlias("user.vehicle_FK", "vehicle", Criteria.INNER_JOIN);
criteria.setProjection(
    Projections.projectionList().add(Projections.groupProperty("user.id"))
                                .add(Projections.countDistinct("user.id")));
0
Philip On

Parameters in Criteria Queries The following query string represents a JPQL query with a parameter: SELECT c FROM Country c WHERE c.population > :p An equivalent query can be built using the JPA criteria API as follows:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Country> q = cb.createQuery(Country.class);
Root<Country> c = q.from(Country.class);
ParameterExpression<Integer> p = cb.parameter(Integer.class);
q.select(c).where(cb.gt(c.get("population"), p));

The ParameterExpression instance, p, is created to represent the query parameter. The where method sets the WHERE clause. As shown above, The CriteriaQuery interface supports method chaining. See the links in the next sections of this page for detailed explanations on how to set criteria query clauses and build criteria expressions.

You can find more examples here https://www.objectdb.com/java/jpa/query/criteria

Remember to post an answer when you find one! :)