Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about Criteria.createCriteria in Hibernate API

So I'm still trying to get myself acquainted with the Hibernate Criteria API, and I have this piece of Java code which I would like to seek clarification over.

Criteria c = super.getSession().createCriteria(PpNnCtDetail.class);
c.add(Restrictions.between("commencementDate", fromDate, toDate);

This part I understand what's happening - putting it in terms of SQL it would be something like - correct me if I'm wrong,

SELECT * FROM PpNnCtDetail WHERE commencementDate >= fromDate AND commencementDate <= toDate;

The problem comes with the code following the two lines above.

c = c.createCriteria("nnContractTbl");
c.createCriteria("progCategory").add(Restrictions.in("progCategoryId", allProgCat));
c.createCriteria("acadOrgTbl");
c.createCriteria("serviceType");
c.createCriteria("campusTbl");
return c.list();

What is the first line trying to accomplish? Is that assignment back to c redundant?

In fact, what are the lines c.createCriteria trying to achieve? What would an equivalent SQL query look like? More importantly, what would c.list() return?

like image 468
ohseekay Avatar asked Dec 06 '25 06:12

ohseekay


1 Answers

The assignament on c = c.createCriteria("nnContractTbl"); is redundant, createCriteria and almost all Criteria methods modify the instance they're invoked on, and return the instance itself for method chanining. So you can chain calls like this:

return super.getSession().createCriteria(PpNnCtDetail.class)
    .add(Restrictions.between("commencementDate", fromDate, toDate)
    .createCriteria("nnContractTbl")
    .createCriteria("progCategory").add(Restrictions.in("progCategoryId", allProgCat))
    .createCriteria("acadOrgTbl")
    .createCriteria("serviceType")
    .createCriteria("campusTbl")
    .list();

And about the result of that sequence, Criteria.createCriteria(association) will result in an inner join between the data already in the criteria and the table designed in the association modelled by the attribute association. It will also "root" (as they state in the Javadocs) the Criteria at the association entity, so that in further calls to createCriteria(association), association refers to an association attribute declared on the last "rooted" entity.

It's a shorthand for Criteria.createCriteria(association, joinType) with joinType CriteriaSpecification.INNER_JOIN.

like image 155
Xavi López Avatar answered Dec 08 '25 18:12

Xavi López