Hibernate Native SQL

vembubalaji
8,652 views

Open Source Your Knowledge, Become a Contributor

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

Create Content

Basic Result set mapping using @SqlResultSetMapping

A quick sample. Check out the JAVA class and SQL file
// {...}
List<Domain> results = session
.createNativeQuery("SELECT domain_id as id, domainName as name FROM domain", "DomainResult")
.getResultList();
results.stream().forEach(result -> {
System.out.println((String.format("Info : team[ %d, %s ]", result.getDomainId(), result.getDomainName())));
});
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  • If the column names of the query result does not match the column names of the entity mapping, then we would have to map the two manually. We can do this using the @SqlResultSetmapping, which specifies the mapping for each attribute.
  • As we can see from the above code, the @SqlResultSetMapping constitutes of a name attribute and a @EntityResult annotation that defines the mapping to the entity.
  • Now, we need to specify the class of the entity and a set of @FieldResult annotation that defines the mapping between the result set column and the entity attribute.
  • To utilize this mapping in the createNativeQuery method we can provide its name as the second parameter. Check the above code snip.
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content