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.
Now, Hibernate can use lazy loading, which means it will load only the required classes, not all classes. It prevents a huge load since the entity is loaded only once when necessary. Lazy loading improves performance by avoiding unnecessary computation and reduce memory requirements.
To enable lazy loading explicitly you must use “fetch = FetchType. LAZY” on an association that you want to lazy load when you are using hibernate annotations. @OneToMany( mappedBy = "category", fetch = FetchType.
In eager loading strategy, if we load the User data, it will also load up all orders associated with it and will store it in a memory. But when we enable lazy loading, if we pull up a UserLazy, OrderDetail data won't be initialized and loaded into a memory until we make an explicit call to it.
Use Hibernate.initialize()
within @Transactional
to initialize lazy objects.
start Transaction Hibernate.initialize(entity.getAddresses()); Hibernate.initialize(entity.getPersons()); end Transaction
Now out side of the Transaction you are able to get lazy objects.
entity.getAddresses().size(); entity.getPersons().size();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With