This week's book giveaway is in the Java in General forum.
We're giving away four copies of Think Java: How to Think Like a Computer Scientist and have Allen B. Downey & Chris Mayfield on-line!
See this thread for details.
Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Writing a JPA query against a member field that's a Set

 
Dave Alvarado
Ranch Hand
Posts: 436
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm using JPA 2.0 and Hibernate 4.1.0.Final. I'm curious how I would write a specific entity manager query. I have a domain object



and then the Contract domain object has



Given a java.util.List of Products, how do I construct a query asking for Users who have at least one contract tied to a product in the given list?

Thanks, - Dave
 
Emanuel Kadziela
Ranch Hand
Posts: 187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You say you have a List of Products already, so I assume you already queried the database for this, correct?

Now, is your question about how to find the users who have contracts related to the products in this list? Or do you want to write the full query which queries the database for a list of users who have contracts related to products in the list and pass the whole list as a query parameter?
 
Dave Alvarado
Ranch Hand
Posts: 436
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> Now, is your question about how to find the users who have contracts related to the products in this list?

Yes, that's what I want. I think I'm close. I have ...



but I can't figure out how to write the last line. The above dodsn't work because "contracts" are different objects than "products".
 
Emanuel Kadziela
Ranch Hand
Posts: 187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe you need to use a Restriction. I copied the following from hibernate docs:



So in your case it should look like this:

 
Dave Alvarado
Ranch Hand
Posts: 436
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks but there are a couple of problems with that approach. In your clause, you are asking for products in contracts, but those two lists contain different objects. A contract has a product, and I'd like to know of the given list of products, what contracts contain a product that match.

Also, I'm trying to use the more generic JPA API, using entityManager, and so I'm trying to eliminate any Hibernate-specific APIs.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic