Skip to content Skip to sidebar Skip to footer

Hibernate HQL Query : How To Set A Collection As A Named Parameter Of A Query With Composite Key?

Given the following HQL Query: from Foo foo where foo.id in (:fooIds) but here i have composite key in the Id ex we have two PK1 and pk2 as Id's. How can we implement this query..

Solution 1:

Are you using a composite id? Do you have a separate class representing the composite-id or do you have 2 fields in Foo and you want to search using them in your query? Posting you Foo class would help!


Solution 2:

I'm not 100% sure you can use in in this case. One thing you can do is to build the query manually with something like

 String hqlQuery = "from Foo foo where "
 boolean first = true;
 for( ID id : fooids ) {
     if( first ) {
          hqlQuery += "foo.id = ?";
          first = false;
     } else {
          hqlQuery += " OR foo.id = ?";
     }
  }

  Query q = em.createQuery(hqlQuery);
  int position = 0;
  for( ID id : fooids ) {
      q.setParameter(position, id);
      position++;
  }

You might want to double check the code, as I'm writing it here, so there's a big chance there's a typo or two.


Post a Comment for "Hibernate HQL Query : How To Set A Collection As A Named Parameter Of A Query With Composite Key?"