Hello,
I wanted to ask the best method possible to initialize objects that are lazy loaded.
I have been developing the last couple of weeks with lazy="false" so I did not have to bother much with optimizing database code.
Yet now the time has come to optimise the database code.
As soon as I started coding this question popped in my mind:
- Open session in view?
- Hibernate.initialize()'ing ?
- Big select clauses & casting them to the object
Now I am not a big fan of open session in view, so I focussed on the latter two.
What do you think is better in practice? (in performance and mvc terms)
Example 1) Big select clauses & casting them to the object
Code:
function retrieveUserInfo( User user)
{
initHibernate();
Object[] loginResult = (Object[]) getSession().createQuery( "select u.userId, u.userName, u.userFirstName, u.userLastName, u.userAge, u.userCountry, u.userCity, u.userPostalCode, u.userAddress, u.userEmail, u.profile.profileName from User u where u.userId = '"+ user.getUserId() +"'").uniqueResult();
getTransaction().commit();
if( loginResult == null)
{
return null;
}
user.setUserId( (Integer) loginResult[0]);
user.setUserName( (String) loginResult[1]);
user.setUserFirstName( (String) loginResult[2]);
// etc.
Profile profile = new Profile();
profile.setProfileName( (String) loginResult[10]);
user.setProfile( profile);
return user;
}
This works fine but this function is hard to maintain.
2) Hibernate.initialize()'ingCode:
function retrieveUserInfo( User user)
{
initHibernate();
User tempUser = (User) getSession().createQuery(
"from User u where u.userId = '"+ user.getUserId() +"'").uniqueResult();
getTransaction().commit();
if( user == null)
{
return null;
}
Hibernate.initialize( user.getUserId());
Hibernate.initialize( user.getUserName());
Hibernate.initialize( user.getUserFirstName());
// etc.
Hibernate.initialize( user.getProfile().getProfileName);
return user;
}
I am using normal properties to keep it simple (in the real situation it is more about the performance hitting collections).
I hope someone could provide me with what is the best way to do it, these 2 methods, or open session in view, or even something totally else.