Moon
Moon

Reputation: 3037

Preferred way to implement @OneToMany lazy fetch of child

I am new to JPA and creating a sample app using Hibernate with Spring. From various posts and Google I found few approaches to implement the LAZY fetch.

Please explain the preferred way of implementation that I may choose. Thanks.

Upvotes: 0

Views: 194

Answers (1)

Henry Leu
Henry Leu

Reputation: 2274

The good way is the second way.

Open session in view pattern is sort of anti-pattern practice. It gives chances to change entities in JSP/Servlet level. It's not safety to data and is a bad programming practice.

The perfered way is to manually load the lazily-loading fields of an entity before using it or use fetch reserved word in HQL statement. what/which data you will use in view layer is the thing you should know in advance by yourself, so the duty to prepare/load data before use them is yours, it's common sense thing.

Here are some ways to load lazily-loading fields in advance:

  1. Set fetch mode to get field value eagerly when querying

    Criteria.setFetchMode(String associationPath, FetchMode mode);

  2. Hibernate.initialize() method to initialize proxy field.

  3. add fetch in HQL statement.

    select emp from Employee as emp fetch join on emp.dept as dept where dept.name like 'HR'

Upvotes: 2

Related Questions