Hibernate Native SQL
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Basic Result set mapping using @SqlResultSetMapping
A quick sample. Check out the JAVA class and SQL file
1
42
43
44
45
46
47
48
49
50
51
// {
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())));
});
}
}
Enter to Rename, Shift+Enter to Preview
1
Enter to Rename, Shift+Enter to Preview
1
package com.tu.hibernate.entity;
Enter to Rename, Shift+Enter to Preview
- 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