我得到了一个典型的订单和物品的实体关联。为了使只读订单成为可能,项目设置为默认FetchType.LAZY。2级和查询缓存已启用。要读取具有关联项目的订单,我正在使用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>();
...
}
Run Code Online (Sandbox Code Playgroud)
项目:
@Entity
@Cacheable
@Table(...)
public class Item extends ... {
@ManyToOne
@JoinColumn(name = "order_id", nullable = false)
private Order order;
...
}
Run Code Online (Sandbox Code Playgroud)
道:
public class OrderDaoJpaImpl extends …Run Code Online (Sandbox Code Playgroud) 我在Tomcat 7中运行的Web应用程序中使用Spring 3.2和JPA以及Hibernate 4.应用程序分为控制器,服务DAO类.服务类在类和方法级别具有带注释的事务配置.DAO是普通的JPA,实体管理器由@PersistenceContext注释注入.
@Service("galleryService")
@Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
public class GalleryServiceImpl implements GalleryService {
@Override
public Picture getPicture(Long pictureId) {
return pictureDao.find(pictureId);
}
@Override
public List<PictureComment> getComments(Picture picture) {
List<PictureComment> comments = commentDao.findVisibleByPicture(picture);
Collections.sort(comments, new Comment.ByCreatedOnComparator(Comment.ByCreatedOnComparator.SORT_DESCENDING));
return comments;
}
...
}
@Controller
@RequestMapping("/gallery/displayPicture.html")
public class DisplayPictureController extends AbstractGalleryController {
@RequestMapping(method = RequestMethod.GET)
public String doGet(ModelMap model, @RequestParam(REQUEST_PARAM_PICTURE_ID) Long pictureId) {
Picture picture = galleryService.getPicture(pictureId);
if (picture != null) {
model.addAttribute("picture", picture);
// Add comments
model.addAttribute("comments", galleryService.getComments(picture));
} else {
LOGGER.warn(MessageFormat.format("Picture {0} …Run Code Online (Sandbox Code Playgroud)