Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need Help Figuring Out A Hibernate Criteria Query

 
Jason Ferguson
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Jason
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

Mark
 
Jason Ferguson
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic