It's not a secret anymore!
The moose likes Object Relational Mapping and the fly likes Need Help Figuring Out A Hibernate Criteria Query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Need Help Figuring Out A Hibernate Criteria Query" Watch "Need Help Figuring Out A Hibernate Criteria Query" New topic

Need Help Figuring Out A Hibernate Criteria Query

Jason Ferguson
Ranch Hand

Joined: Aug 09, 2007
Posts: 58
I need assistance figuring out a criteria query. Here's my use case:

I have an Equipment Item. The Equipment Item belongs to an Account. Also, this Equipment Item can be part of a Package. The Package can be Pending or Completed. I want to be able to query and get all Equipment Items belonging to a given account that either are not part of a Package, or the Package is pending.

Restricting to the account is simple enough (I'm using Spring's HibernateTemplate, so the DetachedCriteria class is used in place of Criteria):

public List<EquipmentItem> getCurrentByAccount(Account a) {

DetachedCriteria equipmentItemCriteria = DetachedCriteria.forClass(EquipmentItem.class);
DetachedCriteria accountCriteria = equipmentItemCriteria.createCriteria("account");
accountCriteria.add(Restrictions.eq("id", a.getId());


Now here's where it gets dicey. I need to do a Restrictions.isNull() on the "package" attribute of the EquipmentItem and OR that with new Criteria on the "package" attribute and get its Pending status.

Since this "crosses" criteria, I don't know how to proceed.

Any advise?

Mark Spritzler

Joined: Feb 05, 2001
Posts: 17276

I just wonder if this is a case where you might be better off with HQL instead. There are definitely ways to make a criteria object out of that query, but it might be more complex to do so. There are lots of objects to use with the Criteria object to do joins, and also "AND and ORs" in any combination.

But I recommend doing it in HQL


Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
Jason Ferguson
Ranch Hand

Joined: Sep 16, 2007
Posts: 47
I try to avoid HQL, but mostly out of personal preference. I can handle the HQL, if necessary, but would like to be consistent through my code and use Criteria.
I agree. Here's the link:
subject: Need Help Figuring Out A Hibernate Criteria Query
It's not a secret anymore!