Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: best practice to pull all lazy collections

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.

like image 401
VB_ Avatar asked Nov 12 '13 11:11

VB_


People also ask

What is the result of lazy loading strategy in Hibernate degrade performance?

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.

How do you load a lazy object in Hibernate?

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.

What is the difference between lazy loading and eager fetching?

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.


1 Answers

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(); 
like image 119
Prabhakaran Ramaswamy Avatar answered Nov 15 '22 13:11

Prabhakaran Ramaswamy