Friday, November 23, 2012

ResultTransformer in Hibernate

Retrieving a non managed entity from database using hibrnate.

If an entity is not mapped to the configuration file and we try to retrieve it from the database generatlly it throws mapping exception.

To get ride of such a situation we can user ResultTranform to retrieve the datafrom the database and map it to a bean which is not an entity or mapped in configuration.

Cautions:Attributes name and datatype in bean and the database should be same.

See the below the snap of code to implement ResultTransformer.

            Session session=Connector.getSession();
            Transaction tx=session.beginTransaction();
                  
           Query query=session.createSQLQuery("SELECT * FROM customer");
           
           List<Customer> list= query.setResultTransformer(Transformers.aliasToBean(Customer.class)).list()
;
    
     Note: Customer is a non mapped entity it is simple a java bean.

2 comments:

  1. Great!!

    But, how can we map customer table columns with Customer.class properties?

    Your answer will be appreciated.

    Thanks,
    Sanjay

    ReplyDelete
    Replies
    1. Hi Sanjay,

      If the customer bean has the same columns name with setter and getter as defined in the database table then resultTransformer will automatically map the column to the customer bean.

      Delete

Note: Only a member of this blog may post a comment.