我有一个典型的订单和物品实体关联.为了能够只读订单,设置的项是默认的FetchType.LAZY.启用了第二级和查询缓存.要阅读包含相关项目的订单,我正在使用JPQL查询.查询和实体由EHCache缓存.但是在访问项目时的第二次调用时,抛出了LazyInitializationException,因为项目未初始化(未从缓存中恢复).为什么?实施此要求的最佳方法是什么?
订购:
@Entity
@Cacheable
@NamedQueries({
@NamedQuery(name = Order.NQ_FIND_BY_ID_FETCH_ITEMS, query = "SELECT DISTINCT o FROM Order o JOIN FETCH o.items WHERE o.id = :id")
})
@Table(...)
public class Order extends ... {
...
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
// @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private Set<Item> items = new HashSet<Item>();
...
}
项目:
@Entity
@Cacheable
@Table(...)
public class Item extends ... {
@ManyToOne
@JoinColumn(name = "order_id", nullable = false)
private Order order;
...
}
DAO:
public class OrderDaoJpaImpl extends ... {
@Override
public Catalog findByIdFetchItems(Long id) {
TypedQuery<Order> query = entityManager.createNamedQuery(Order.NQ_FIND_BY_ID_FETCH_ITEMS, Order.class);
query.setParameter("id", id);
// query.setHint(QueryHints.HINT_CACHEABLE, Boolean.TRUE);
Order order = JPAUtil.singleResultOrNull(query);
return order;
}
服务:
@Service("orderService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class OrderServiceImpl implements OrderService {
@Override
public Order getOrderWithItems(Long orderId) {
return orderDao.findByIdFetchItems(orderId);
}
}
persistence.xml中:
<persistence ...>
<persistence-unit name="shop-persistence" transaction-type="RESOURCE_LOCAL">
<jar-file>shop-persistence.jar</jar-file>
<!-- Enable JPA 2 second level cache -->
<shared-cache-mode>ALL</shared-cache-mode>
<properties>
...
<property name="hibernate.cache.use_second_level_cache" value="true" />
<property name="hibernate.cache.use_query_cache" value="true" />
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"/>
</properties>
</persistence-unit>
</persistence>
Spring Framework 4.3.7.RELEASE和Hibernate 5.2.9.Final.
如您所见,我尝试使用Hibernate实体注释和缓存提示而不是JPA缓存.我也尝试过JPA实体图而不是JOIN FETCH.始终相同:在订单查询的第二次调用中未初始化/恢复项目.
最佳答案 由于
HHH-12430问题,抛出了LazyInitializationException.
但是,您的代码也存在一些问题,并且在Hibernate HHH-12430问题得到修复之前,您可以使用一种解决方法.
当您使用Hibernate时,使用@Cacheable注释您的实体是不够的.
如this article中所述,您还需要提供缓存并发策略:
@Entity
@org.hibernate.annotations.Cache(usage =
CacheConcurrencyStrategy.READ_WRITE)
查询缓存only stores entity identifiers,由于您只选择订单,因此项目关联也不会被缓存.
你可以做的是将你的查询更改为:
@NamedQuery(name = Order.NQ_FIND_BY_ID_FETCH_ITEMS, query = "SELECT DISTINCT o FROM Order o WHERE o.id = :id")
然后,激活缓存以进行收集:
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private Set<Item> items = new HashSet<Item>();
订单和物品都应该使用:
@Entity
@org.hibernate.annotations.Cache(usage =
CacheConcurrencyStrategy.READ_WRITE)
因为它们需要可缓存.
并确保在返回结果集之前初始化items集合:
Order order = JPAUtil.singleResultOrNull(query);
if(order != null) {
order.getItems().size();
}
return order;
这样,将始终初始化项目,并从缓存中提取集合,而不是从数据库中提取集合.