0

I have an entity class named User which contains this OneToMany column for database:

  @Setter
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
    @JoinTable(
        name = "USER_CARS",
        joinColumns = @JoinColumn(name="USER_ID", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name="CAR_ID", referencedColumnName = "id")
    )
    private List<Car> cars;

When I'm inserting an user into database, everything works fine, and his cars are also added in user_cars table. When retrieving the cars i get this exception:

Method threw 'org.hibernate.LazyInitializationException' exception.

I've searched for other answers but didn't found how to solve it. This is how I'm trying to retrieve the User.

public T findById(Long id) {
    em = emf.createEntityManager();
    em.getTransaction().begin();

    T et = (T) em.find(entityClass, id);

    em.getTransaction().commit();
    em.close();

    return et;
}

What is the problem and how can I fix it? I can't understand what's going on in background.

smotru
  • 433
  • 2
  • 8
  • 24
  • You can test with `fetch = FetchType.EAGER` in `@OneToMany` annotation first. Default fetch type is `Lazy` for many side. I think you have to initialise all cars related to user in transaction bountry with `Hibernate.initialize()` method. See [here](http://stackoverflow.com/questions/5837169/org-hibernate-lazyinitializationexception-how-to-properly-use-hibernates-lazy) and [here](http://stackoverflow.com/questions/14542140/hibernate-org-hibernate-lazyinitializationexception-could-not-initialize-proxy) for more details. – Wundwin Born Jun 02 '14 at 12:07
  • When exactly do you got this exception? You will see it when you try to access lazy-loaded properties when `session` is no longer available. You may want to make it available as an alternative to eager loading. – Alexey Malev Jun 02 '14 at 12:21
  • This exception is seen (while debuging) when trying to see user cars in the retrieved data. – smotru Jun 02 '14 at 14:26

1 Answers1

1

Based on the exception message, it seems that you are retrieving the content of the List cars but the EntityManager session is already closed. Rather than the default lazy initialization for the collection you could use

@OneToMany(cascade = CascadeType.ALL, mappedBy = "user", fetch = FetchType.EAGER)
Reimeus
  • 158,255
  • 15
  • 216
  • 276