Question

I'm writing my apllication using Spring MVC + Hibernate. I have 2 entities: order and items(order items).

Order entity:

@Entity
@Table(name = "orders")
public class Order {

@Id
@GeneratedValue
private int id;

@Column(name = "time")
private long time;

@OneToMany(mappedBy = "order")
private List<Item> items;

Item entity:

@Entity
@Table(name = "items")
public class Item {

@Id
@GeneratedValue
private int

@ManyToOne(targetEntity = Order.class)
private Order order;

@Column
private int count;

I want to list orders in page '/orders', and order's detail in page '/orders/{id}/view'.

In my DAOImpl i write code below:

public List<Order> view() {
    return sessionFactory.getCurrentSession()
            .createCriteria(Order.class)
            .addOrder(org.hibernate.criterion.Order.desc("time"))
            .list();
}

This code returns a list of all orders. But if I try see order's detail I have exception: org.apache.jasper.JasperException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ru.drupo.order.domain.Order.items, could not initialize proxy - no Session.

There are duplicates of orders in list if I add to order's entity fetch = FetchType.EAGER. But order's detail shows correctly.

How I can initialize lazy loading?

Was it helpful?

Solution

While in transaction (within active session) use Hibernate.initialize(order.getItems()) to initialize non-hydrated entities or collections.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top