Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

One to many in a query - EJB QL

jeff mutonho
Ranch Hand
Posts: 271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm using JPA.I have an entity Item that has a one-to-many relationship with a Bid,and I wish to select all the Bids that belong to a particular Item using the EJB QL.
1)How would the SELECT statement look?
2)Since each Item has a getBids() method that returns a list of Bids ,is it sufficient to just do:

and not bother with a SELECT?Does JPA always ensure that if I find an Item (call it item) by doing , then the corresponding bids for the item are also returned with the found item
Mark Spritzler
Posts: 17309
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes and Yes, and also No and No.

OK, so you query an Item. The Bids by default are lazy loaded. Therefore you load (find) an Item, the Bids collection is empty. If you are still in the Unit of Work, when you go through the Bids collection, the bid data will be retrieved from the database.

You can have bids mapped to eager load (eager fetch), In that case, when you load (find) an Item, the Bids collection will be populated with all the related Bids.

So in the first case, you have N+1 queries. 1 for the Item, and 1 for each and every corresponding Bid.

In the second case you have one query that loads it all.

Now, here comes the other possibilities.

You can have the mapping be fetching strategy be "subselect" which means that instead of N+1 queries against the database, you will have 2. One to load the Item, and when you access the bids collection, another query to get all the Bids in one swoop. It uses the first query for Item as a subselect portion of the query to load the bids.

The last option is to set the fetching strategy at time of query, so you won't be able to use find(). You will have to use the Query object, and write something like

"Select i from Items i JOIN FETCH Bids b WHERE i.item_id = :item_id"

In that query I use ":item_id" which is a bind parameter. Always use Bind Parameters.

Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!