我有一个关于代码片段(完整源代码)的询问,这是一本关于 Hibernate/JPA 的书的随附代码示例。
这是代码清单:
public class Subselect extends JPATest {
@Override
public void configurePersistenceUnit() throws Exception {
configurePersistenceUnit("FetchingSubselectPU");
}
public FetchTestData storeTestData() throws Exception {
UserTransaction tx = TM.getUserTransaction();
tx.begin();
EntityManager em = JPA.createEntityManager();
Long[] itemIds = new Long[3];
Long[] userIds = new Long[3];
User johndoe = new User("johndoe");
em.persist(johndoe);
userIds[0] = johndoe.getId();
User janeroe = new User("janeroe");
em.persist(janeroe);
userIds[1] = janeroe.getId();
User robertdoe = new User("robertdoe");
em.persist(robertdoe);
userIds[2] = robertdoe.getId();
Item item = new Item("Item One", CalendarUtil.TOMORROW.getTime(), johndoe);
em.persist(item);
itemIds[0] = item.getId();
for (int i = 1; i <= 3; i++) {
Bid bid = new Bid(item, robertdoe, new BigDecimal(9 + i));
item.getBids().add(bid);
em.persist(bid);
}
item = new Item("Item Two", CalendarUtil.TOMORROW.getTime(), johndoe);
em.persist(item);
itemIds[1] = item.getId();
for (int i = 1; i <= 1; i++) {
Bid bid = new Bid(item, janeroe, new BigDecimal(2 + i));
item.getBids().add(bid);
em.persist(bid);
}
item = new Item("Item Three", CalendarUtil.AFTER_TOMORROW.getTime(), janeroe);
em.persist(item);
itemIds[2] = item.getId();
for (int i = 1; i <= 1; i++) {
Bid bid = new Bid(item, johndoe, new BigDecimal(3 + i));
item.getBids().add(bid);
em.persist(bid);
}
tx.commit();
em.close();
FetchTestData testData = new FetchTestData();
testData.items = new TestData(itemIds);
testData.users = new TestData(userIds);
return testData;
}
@Test
public void fetchCollectionSubselect() throws Exception {
storeTestData();
UserTransaction tx = TM.getUserTransaction();
try {
tx.begin();
EntityManager em = JPA.createEntityManager();
List<Item> items = em.createQuery("select i from Item i").getResultList();
// select * from ITEM
for (Item item : items) {
assertTrue(item.getBids().size() > 0);
// select * from BID where ITEM_ID in (
// select ID from ITEM
// )
}
// The actual test
em.clear();
items = em.createQuery("select i from Item i").getResultList();
// Access should load all collections
assertTrue(items.iterator().next().getBids().size() > 0);
em.clear(); // Detach all
for (Item item : items) {
assertTrue(item.getBids().size() > 0);
}
tx.commit();
em.close();
} finally {
TM.rollback();
}
}
}
我不明白的具体部分是这个:
for (Item item : items) {
assertTrue(item.getBids().size() > 0);
// select * from BID where ITEM_ID in (
// select ID from ITEM
// )
}
它旨在演示使用休眠的子选择功能进行预取以及将要执行的 SQL 查询。
以下注释: // select ID from ITEM
表示从 DB 中检索所有项目 ID。这是子选择预取的工作原理吗?为什么要从表中检索所有ID
s ITEM
?
这是Item
实体:
@Entity
public class Item {
@OneToMany(mappedBy = "item")
@org.hibernate.annotations.Fetch(
org.hibernate.annotations.FetchMode.SUBSELECT
)
protected Set<Bid> bids = new HashSet<>();
// ...
}