I have a Spring app , many-to-many relationship between Order
and Product
with intermediary table ProductOrder
.
If I save the ProductOrder
directly to the db, it works fine, but I don't think that's the correct way, so I use the code below to add an Order
to a Product
by fetching and adding to the lazy collection.
I had a LazyInitializationException
, so I tried to solve it with Hibernate initialize, but now I'm getting org.hibernate.HibernateException: collection is not associated with any session
. I debugged and session=null for the PersistentCollection
. I thought the @Transactional annotation is meant to begin a transaction and open a session, but it doesn't seem to work.
I looked for some answers , and the cause is that the current session is not the same as when the object was created, but I don't know how to try solving the problem, please help me!
(I also have OpenEntityManagerInViewFilter
in web.xml , but it doesn't seem to make any difference in solving this)
@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());
}
Additional info:
@Service("productService")
@Repository
@Transactional
public class ProductServiceImpl implements ProductService{
@Autowired
private ProductRepository productRepository;
@Override
public Product save(Product product) {
return productRepository.save(product);
}
}