【发布时间】:2020-03-03 19:11:45
【问题描述】:
我正面临 LazyInitializationException 的有趣解决方案。 为了防止这种情况(在 OneToMany 或 ManyToMany 上),一种已知的解决方案是使用 JOIN FETCH Query。 你可以看到她的几个例子之一:https://thoughts-on-java.org/best-practices-for-many-to-many-associations-with-hibernate-and-jpa/
其他更简单的解决方案是使用 Spring 中的 @Transactional。 比如这样:
@DeleteMapping(value ="/product/{tagId}")
@ResponseBody
@Transactional
public String deleteProductWithoutRelation(@PathVariable String product, Model model) {
Optional<Product> pr = productService.selectProduct(product);
if (pr.isPresent()) {
tag.get().getCustomer().size(); //usualy throws LazyInitializationException,
//without JOIN-FETCH Statment or @Transactional
return deletedTagId;
}
当然,您可以将存储库服务中的某些方法的@Transactional 放置在此解决方案中。 那么这两种解决方案有哪些优点或缺点呢?
【问题讨论】:
-
控制器不是交易的好地方,见stackoverflow.com/questions/23118789/…
-
@Transactional 不会关闭会话,直到调用结束降低性能。
标签: java spring hibernate jpa lazy-initialization