Thursday, 26 July 2012

Retrieve limited field from table AS A MAP in Hibernate



When you are retrieving limited (e.g. 7-8) fields from tables, you need to remember that which field located on which index. Instead of this you can use map in hibernate to come out from sophisticated work.


**********************************************************************************************************************************
Good Approach : Retrieve multiple properties as a list of type Map<String,String>.
Benefit : Just give alias to properties and use that alias as a key in Map.


                List<Map<String,String>> usermasterMapList = null;

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx=null;
try
{
session.beginTransaction();
usermasterMapList = session.createQuery("select new map(username as username,password                                                as password,role as role) from Usermaster where isdeleted = 'N'").list();

for(int i=0; i<usermasterMapList.size(); i++) {

Map<String,String> usermasterMap = usermasterMapList.get(i);

System.out.println("Username : " + usermasterMap.get("username"));
System.out.println("Password : " + usermasterMap.get("password"));
System.out.println("Role : " + usermasterMap.get("role"));
}
}
catch (RuntimeException e)
{
if(tx != null)
tx.rollback();
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
if(tx != null)
tx.rollback();
}


**********************************************************************************************************************************

Approach : Retrieve multiple properties as a list of type Object[].
Limitations : Must have to remember indices of particular field. Like obj[0],obj[1],obj[2],... and so on.

List<Object[]> usermasterList = null;

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx=null;
try
{
session.beginTransaction();
usermasterList = session.createQuery("select 
                                                 username,password,role from Usermaster where isdeleted = 'N'").list();


                  for(int i=0; i<usermasterList.size(); i++) {

Object[] obj = usermasterList.get(i);

String username = obj[0].toString();
String password = obj[1].toString();
String role = obj[2].toString();
  
        System.out.println("Username :: " + username);
System.out.println("Password :: " + password);
System.out.println("Role :: " + role);


}
catch (RuntimeException e)
{
if(tx != null)
tx.rollback();
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
if(tx != null)
tx.rollback();
}

**********************************************************************************************************************************