7
Friends, all good?
I have a problem that is the famous: org.hibernate.Lazyinitializationexception:.
I know this is because the session has been closed and Hibernate can’t connect to make the selects and etc, but then how to get the data after the session is closed?
For example: I have these classes:
State:
public class State {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@OneToOne
@JoinColumn(name = "id_country")
private Country country;
private String description;
private String uf;
@OneToOne
@JoinColumn(name = "id_timezone")
private TimeZone timeZone;
@OneToMany(mappedBy = "state", targetEntity = City.class, fetch = FetchType.LAZY)
@OrderBy("description asc")
private Set<City> city;
/get e set
}
City:
public class City implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@OneToOne
@JoinColumn(name = "id_state")
private State state;
private String description;
//get e set
}
Person:
public class Pessoa {
private Long id;
private String name;
private City city;
/get e set
}
If I leave in EAGER mode the list of cities in the state entity and every time catch a new person it will end up doing several selects picking up all the cities of that state. However, if I leave in LAZY mode and need to access my city list I get the exception ** org.hibernate.Lazyinitializationexception** because the connection is closed.
How to get around this problem? Someone of a hand?
I suggest keeping the list of cities as Lazy load and force-load them into the status repository. Thus, any entity that has a relationship to the state will not upload the list of cities. When the app is interested in the list of cities it will surely be loading the state from the state repository and not from a relationship - and by then the list of cities will be loaded.
– Caffé
Thank you very much for the suggestion
– Paulo Gustavo
We need more details to understand your problem. For example, what part of your code opens and closes the Hibernate session? Or are you using some framework (Sprign, EJB, etc) to manage the session? If so, how is it configured? Where does the call in Lazyinitializationexception occur in your code? Anyway, that’s a lot of details we need to know to give you an accurate answer.
– Dherik