问题
I am reading the book "Java Persistence with Hibernate, 2nd Edition". It takes an example of items sold to bidders like ebay. At the page 400, the author says
The query
select i from item i left join fetch i.bids b where b.amount > 20
is invalid. You can’t say, “Load the Item instances and initialize their bids collections, but only with Bid instances that have a certain amount.”
I am not sure to quite understand. To my opinion it is valid, but it will renders only the items that have a bid which amount is greater than 20. It will render in that case an inner join with that condition
Furthermore is the following request select i from item i left join fetch i.bids b on b.amount > 20
valid?
回答1:
select i from item i left join fetch i.bids b where b.amount > 20
as HQL is invalid. Because the HQL results is used to return Item objects, you cannot tell hibernate to please create Item
objects but when you create it, do not populate it with all Bid
s but populate only with Bid
s with amount greater than 20.
Consider the following class
public class Item {
String name;
Collection<Bid> bids;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection<Bid> getBids() {
return bids;
}
public void setBids(Collection<Bid> bids) {
this.bids = bids;
}
}
Update: (Lets run through an example to see what would have happened if hibernate allowed this query)
Major issues if hibernate had allowed it to happen:
- First issue this will be conceptually wrong because any service using the item1 java object that was returned from the repo does not know item.getBids only contains bid with amount > 20
- Hibernate only keeps one object reference to represent a database entity in a session (Repeatable Read guarantee, dirty checking etc). So if you do another
Select i from Item i where i.itemId = 1
, hibernate has a problem because now it has to have two java objects to represent item 1 in that session (one with bids where the amount > 20 and another with all bids of item1)
Hope this explains clearly why the query can't be allowed
来源:https://stackoverflow.com/questions/62473979/use-case-in-the-book-java-persistence-with-hibernate-2nd-edition