我面临着LazyInitializationException的有趣解决方案。为了防止这种情况(在OneToMany或ManyToMany上),一种已知的解决方案是使用JOIN FETCH查询。您可以看到以下几个例子之一: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,以封装此解决方案。那么,这两种解决方案的优缺点在哪里?
我们需要在这里解开几件事。
推荐:您应该尝试使用适当的JPQL / Criteria / SQL语句获取呈现视图所需的所有数据,而不要过多地依赖重新选择惰性字段。