smotru
smotru

Reputation: 431

Hibernate/Jpa OneToMany not retrieving data properly

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.

Upvotes: 0

Views: 2562

Answers (1)

Reimeus
Reimeus

Reputation: 159784

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)

Upvotes: 1

Related Questions