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.