What I have:
@Entity
public class MyEntity {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
@JoinColumn(name = "myentiy_id")
private List<Address> addreses;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
@JoinColumn(name = "myentiy_id")
private List<Person> persons;
//....
}
public void handle() {
Session session = createNewSession();
MyEntity entity = (MyEntity) session.get(MyEntity.class, entityId);
proceed(session); // FLUSH, COMMIT, CLOSE session!
Utils.objectToJson(entity); //TROUBLES, because it can't convert to json lazy collections
}
What a problem:
The problem is that I can't pull lazy collection after session has been closed. But I also can't not close a session in proceed method.
What a solution (coarse solution):
a) Before session is closed, force hibernate to pull lazy collections
entity.getAddresses().size();
entity.getPersons().size();
....
b) Maybe more ellegant way is to use @Fetch(FetchMode.SUBSELECT)
annotation
Question:
What is a best practice/common way/more ellegant way to do it? Means convert my object to JSON.
With Hibernate 4.1.6 a new feature is introduced to handle those lazy association problems. When you enable hibernate.enable_lazy_load_no_trans property in hibernate.properties or in hibernate.cfg.xml, you will have no LazyInitializationException any more.
For More refer : https://stackoverflow.com/a/11913404/286588
It's probably not anywhere approaching a best practice, but I usually call a
SIZE
on the collection to load the children in the same transaction, like you have suggested. It's clean, immune to any changes in the structure of the child elements, and yields SQL with low overhead.if you using jpa repository, set properties.put("hibernate.enable_lazy_load_no_trans",true); to jpaPropertymap
Not the best solution, but here is what I got:
1) Annotate getter you want to initialize with this annotation:
2) Use this method (can be put in a generic class, or you can change T with Object class) on a object after you read it from database:
Try use
Gson
library to convert objects to JsonExample with servlets :
Place the Utils.objectToJson(entity); call before session closing.
Or you can try to set fetch mode and play with code like this