使用find()和查询的Hibernate刷新行为

时间:2019-07-24 15:11:34

标签: java hibernate jpa flush

ItemBidSummary类

@org.hibernate.annotations.Subselect(
    value = "select i.ID as ITEMID, i.ITEM_NAME as NAME, " +
            "count(b.ID) as NUMBEROFBIDS " +
            "from ITEM i left outer join BID b on i.ID = b.ITEM_ID " +
            "group by i.ID, i.ITEM_NAME"
)
@org.hibernate.annotations.Synchronize({"Item", "Bid"})
public class ItemBidSummary {
    // ...
}

测试用例代码段

Item item = em.find(Item.class, ITEM_ID);
item.setName("foo");

// No flush before retrieval by identifier!
// ItemBidSummary itemBidSummary = em.find(ItemBidSummary.class, ITEM_ID); // #1

// Automatic flush before queries if synchronized tables are affected!
Query query = em.createQuery( "select ibs from ItemBidSummary ibs where ibs.itemId = :id" ); // #2
ItemBidSummary itemBidSummary = (ItemBidSummary)query.setParameter("id", ITEM_ID).getSingleResult(); // #3

assertEquals(itemBidSummary.getName(), "foo");

如果未注释#1,并且注释了#2和#3,则测试用例失败。 Hibernate会在调用#3之前刷新并更新项目实例,但不会为#1刷新。为什么?

0 个答案:

没有答案