May be for optimization of JVM memory we need partial loaded object with only specified fields with values from DB .
Without using projection you can get such partially loaded by using transformer .
But I think following code is elegant example ..
1. DB TABLE
USER_TABLE , DB Table >>
columns
USER_ID (INT(10))
USER_NAME(VARCHAR(50))
2. MODEL CLASS
User.java - Model Class
Public class User{
private int userId;
private String userName ;
..
..
..
AND MANY OTHER PROPERTIES
// Getters and Setters for id and name and for other props
}
3. Hibernet settings
In hibernet config xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.salpe.dao.model.User"
lazy="false" table="USER_TABLE" >
<id name="userId" column="USER_ID"/>
<property name="userName" column="USER_NAME" />
---
------
----
<!--MANY OTHER PROPERTIES -->
</class>
</hibernate-mapping>
4. DAO class
SessionFactoryUtil >> Way to get hibernet session
Public class UserDaoImpl {
public static List<User> getPariallyLoadedUsers(int userId){
Criteria crit = SessionFactoryUtil.getInstance().getCurrentSession()
.createCriteria(User.class);
ProjectionList usrList = Projections.projectionList();
// Laoding only user id and user name and Other properties as Null or default 0 ;
proList.add(Projections.property("userId"),"userId");
proList.add(Projections.property("userName"),"userName");
crit.setProjection(usrList);
crit.add(Restrictions.eq("userId",Integer.toString(projectId)));
crit.setResultTransformer(
Transformers.aliasToBean(User.class));
List<User> list = crit.list();
return list;
}
NOTE : FOR DB OPTIMIZATION IS BETTER TO OPTIMIZE ON NUMBER OF ROWS QUERY IS FETCHING RATHER THAN ON NUMBER OF FIELDS/COLUMNS.But I am giving this as just example .