开发者

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.createCriter开发者_如何转开发ia("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?


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.


Those createCriteria as specified above are basically equivalent to an INNER JOIN to the entity passed.

The best way to find answers to your questions (and also learn hibernate in the meantime) is to turn SQL logging on in your hibernate configuration file, and inspect the generated SQL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜