Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Object Relational Mapping and the fly likes One to many in a query - EJB QL Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "One to many in a query - EJB QL" Watch "One to many in a query - EJB QL" New topic
Author

One to many in a query - EJB QL

jeff mutonho
Ranch Hand

Joined: Apr 30, 2003
Posts: 271
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
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17250
    
    6

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.

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: One to many in a query - EJB QL