Quantcast
Viewing all articles
Browse latest Browse all 76

Solve LazyInitializationException in spring, hibernate ?

I have a Spring app , many to many relationship between Order and Product with intermediary 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 the connection to a Product by fetching and adding to a 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 is null . I thought the @Transactional annotation is meant to create 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. 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)

Code:

        @Transactional
        public void addClient(...)
        {
                ...
                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());

}


Viewing all articles
Browse latest Browse all 76

Trending Articles