我有一个Spring应用,Order
和Product
与中间表ProductOrder
之间的多对多关系。
如果我将ProductOrder
直接保存到数据库,它可以正常工作,但我不认为这是正确的方法,因此我使用下面的代码将Order
添加到Product
1}}通过获取和添加到惰性集合。
我有一个LazyInitializationException
,所以我尝试用Hibernate初始化来解决它,但现在我得到了org.hibernate.HibernateException: collection is not associated with any session
。我为PersistentCollection
调试了session = null。我认为@Transactional注释意味着开始一个事务并打开一个会话,但它似乎不起作用。
我寻找了一些答案,原因是当前会话与创建对象时不一样,但我不知道如何尝试解决问题,请帮助我!
(我在web.xml中也有OpenEntityManagerInViewFilter
,但在解决这个方面似乎没有任何区别)
@Transactional
public void addClient(RequestContext context,ShoppingCart cart)
{
...
List<Item> items = cart.getItems();
Order order = new Order();
order.setClient(client);
order.setDate(new Date());
order = orderService.save(order);
for(Item item : items)
{
ProductOrder po = new ProductOrder();
po.setOrder(order);
po.setProduct(item.getProduct());
Hibernate.initialize(item.getProduct().getProductOrders());
item.getProduct().getProductOrders().add(po);
productService.save(item.getProduct());
}
其他信息:
@Service("productService")
@Repository
@Transactional
public class ProductServiceImpl implements ProductService{
@Autowired
private ProductRepository productRepository;
@Override
public Product save(Product product) {
return productRepository.save(product);
}
}