Wednesday, June 20, 2012

Hibernate : A workaround for avoiding explicitly setting DTO object properties from entity object

Using HQL query

Query query = sessionFactory.
getCurrentSession().createQuery("select custType.customerTypeId as customerTypeId, custType.customerTypeName as customerTypeName from CustomerType custType");

List<CustomerTypeData> customerTypeDataList =  query.setResultTransformer(Transformers.aliasToBean(CustomerTypeData.class)).list();       

 
 
 
Using Criteria

List<CustomerTypeData> customerTypeDataList  = sessionFactory.getCurrentSession()
                .createCriteria(CustomerType.class)
                .setProjection(
                        Projections.projectionList().add(
                                Projections.property("customerTypeId"),
                                "customerTypeId").add(Projections.property("customerTypeName"),
                                "customerTypeName"))
                .setResultTransformer(
                        Transformers.aliasToBean(CustomerTypeData.class)).list();

No comments: