Problems with lazy Hibernate


Friends, all good?

I have a problem that is famous: org.hibernate.LazyInitializationException: .

I know this is because the session has been closed and hibernate can not connect to make the selects and so on, but then how do I get the data after the session is closed?

For example: I have these classes:

Status :

public class State  {

@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@JoinColumn(name = "id_country")
private Country country;
private String description;
private String uf;
@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 {

    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    @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 I pick up a new person it will end up making several selects picking up all the cities of that state. However, if I leave in LAZY mode and need access to my city list I get the ** org.hibernate.LazyInitializationException ** exception because the connection is closed.

How to work around this problem? Does anyone give a hand?

asked by anonymous 20.05.2015 / 15:47

2 answers


Hello. The problem is how hibernate will handle the relationships between your classes. You used the fetch = FetchType.LAZY attribute. With this it does not magically "pick" the list of related cities and at some point its application is doing something like ... State.getCity (). There are at least two ways to solve this.

1 - You must complete this list before using it. Try to implement some method like ... public List getCitiesByState (State s) {};

2 - You can change how hibernate handles this relationship by changing the fetch = FetchType.LAZY attribute to fetch = FetchType.EAGER     

28.12.2016 / 18:31

I do not know how you're doing your query, but use JOIN FETCH in it, so Hibernate will initialize the objects that are mapped as lazy .

HQL example:

22.11.2015 / 13:46