1

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?

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.