Reputation: 3037
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.
select p from Partner p join fetch p.contacts where...
).Please explain the preferred way of implementation that I may choose. Thanks.
Upvotes: 0
Views: 194
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:
Set fetch mode to get field value eagerly when querying
Criteria.setFetchMode(String associationPath, FetchMode mode);
Hibernate.initialize() method to initialize proxy field.
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