Chapter 8. Native query
You may also express queries in the native SQL dialect of your database. This is useful if you want to utilize database specific features such as query hints or the CONNECT BY option in Oracle. It also provides a clean migration path from a direct SQL/JDBC based application to Hibernate. Note that Hibernate allows you to specify handwritten SQL (including stored procedures) for all create, update, delete, and load operations (please refer to the reference guide for more information.)
8.1. Expressing the resultset
To use a SQL query, you need to describe the SQL resultset. This description will help the
EntityManager
to map your columns onto entity properties. This is done using the @SqlResultSetMapping
annotation. Each @SqlResultSetMapping
has a name wich is used when creating a SQL query on EntityManager
.
@SqlResultSetMapping(name="GetNightAndArea", entities={ @EntityResult(entityClass=org.hibernate.test.annotations.query.Night.class, fields = { @FieldResult(name="id", column="nid"), @FieldResult(name="duration", column="night_duration"), @FieldResult(name="date", column="night_date"), @FieldResult(name="area", column="area_id") }), @EntityResult(entityClass=org.hibernate.test.annotations.query.Area.class, fields = { @FieldResult(name="id", column="aid"), @FieldResult(name="name", column="name") }) } ) @SqlResultSetMapping(name="defaultSpaceShip", entities=@EntityResult(entityClass=org.hibernate.test.annotations.query.SpaceShip.class))
You can also define scalar results and even mix entity results and scalar results
@SqlResultSetMapping(name="ScalarAndEntities", entities={ @EntityResult(entityClass=org.hibernate.test.annotations.query.Night.class, fields = { @FieldResult(name="id", column="nid"), @FieldResult(name="duration", column="night_duration"), @FieldResult(name="date", column="night_date"), @FieldResult(name="area", column="area_id") }), @EntityResult(entityClass=org.hibernate.test.annotations.query.Area.class, fields = { @FieldResult(name="id", column="aid"), @FieldResult(name="name", column="name") }) }, columns={ @ColumnResult(name="durationInSec") } )
The SQL query will then have to return a column alias
durationInSec
.
Please refer to the Hibernate Annotations reference guide for more information about
@SqlResultSetMapping.