This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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
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.