Hibernate Native SQL

vembubalaji
1,472 views
undefined

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content
Previous: Mapping Non-managed entities via result transformer

Custom Transformers!

  • In case the columns returned from the result set names does not match the names on the mapped JavaBean attributes, and then we opt for the explicit transformation.
A quick sample. Check out the JAVA class and SQL file
// {...}
List<Object[]> users = session.createNativeQuery(
"SELECT user_Id,name,username,isadmin,region_id,team_id,domain_id FROM user u where u.user_id=?")
.setParameter(1, 1).list();
users.stream().forEach(objects -> {
Integer id = (Integer) objects[0];
String name = (String) objects[1];
System.out.println(String.format("Info: User[ %d, %s ]", id, name));
});
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  • Here, we would implement ResultTransformer interface and override the transformTuple and transformList methods.
  • The actual object building logic is present in the transformTuple method. The input argument for the method are an object array of the column alias (aliases) and respective column values (tuple).
  • Please note, this has been depreciated since hibernate v5.2, with no new approach being proposed- https://discourse.hibernate.org/t/hibernate-resulttransformer-is-deprecated-what-to-use-instead/232
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content