Friday, 28 December 2012

Retrieve limited field in hibernate

Assume we have hibernate generated POJO like

public class Customermaster implements java.io.Serializable {

private Integer customerId;
private String companyName;
private String contactPersonName;
private String contactNumber;
private String customerWebsite;
private String customerAddress1;
private String customerAddress2;
private String customerEmail;
private String customerZipCode;
private String customerCity;
private String customerState;
private String customerCountry;

        . . .
        .....
        . . .
}

Now we want only customerId, companyName and contactNumber in pojo object instead of Object[] or Map.

For that create constructor of that limited fields in pojo class.
Here we create contructor like

public Customermaster(Integer customerId, String companyName, String       contactNumber ) 
{
this.customerId = customerId;
this.companyName = companyName;
                this.contactNumber  = contactNumber ;
}

And finally we write query in dao like

List<Customermaster> customerList  =  List<Customermaster>)session.createQuery("select new Customermaster(cm.customerId ,cm.companyName, cm.contactNumber ) from Customermaster cm where .... ").list();

and we have list of Customermaster with only three fields, remains are null.