use case in the book “Java Persistence with Hibernate, 2nd Edition”

纵然是瞬间 提交于 2020-07-22 06:15:09

问题


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 Bids but populate only with Bids 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:

  1. 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
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!