Back
Close

Hibernate Native SQL

vembubalaji
1,450 views

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.
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants