Wednesday, January 11, 2012

Result Transformers in Hibernate


ResultsetTransformers
=======================
The ResultTransformer is a nice and simple interface that allows you to transform any Criteria result element. E.g. you can make any Criteria result be returned as a java.util.Map

Using result set transformers we can transform the result in to java object at the time of querying.
For example in the below code I am retrieving stock name from stock class  and record ID from
Stock daily record class and at querying time , we are assigning the result set to stockRecord class.

//ResultTransformer
       
/* when we query different classes and we want to cast into one class
*   we have to set the properties instead of that we can use setResultTransformers */
       
Criteria crit7 = session.createCriteria(Stock.class).createAlias("stockDailyRecords", "sdr");
crit7.add( Restrictions.like("stockName", "s%") ).setProjection( Projections.projectionList().add(Projections.property("stockName"),"sName")
.add(Projections.property("sdr.recordId"),"rId")).setResultTransformer(Transformers.aliasToBean(StockRecord.class));
List<StockRecord> records7 = crit7.list();
System.out.println("Using ResultTransformer with Transformers.aliasToBean"); 
for(StockRecord sr:records7) {
      System.out.println(sr.getSName());
}

See the below sample codes for more examples

/*native SQl   with add entity*/
           
Query crit8= session.createSQLQuery("select stock_id,stock_name,stock_code from stock").addEntity(Stock.class);
System.out.println("Using add entity to a native sql");
List<Stock> reocrds8=crit8.list(); 
for(Stock stock:reocrds8) {
     System.out.println(stock.getStockName());
}

No comments: