Hibernate JPA @NamedNativeQuery Example

@NamedNativeQuery

The @NamedNativeQuery annotation extends the JPA @NamedNativeQuery with Hibernate specific features, like:


  • flush mode for this particular query
  • if the query should be cached, and which cache region should be used
  • the selected entity CacheModeType strategy
  • the JDBC Statement fetch size
  • the JDBC Statement execution timeout
  • if the query is a CallableStatement, targeting a stored procedure or a database function
  • what SQL-level comment should be sent to the database


if the query is read-only, hence it does not store the resulted entities into the currently running Persistence Context

 Hibernate NamedNativeQuery

@NamedNativeQueries({
    @NamedNativeQuery(
        name = "get_person_phone_count",
        query = "SELECT pr.name AS name, count(*) AS phoneCount " +
                "FROM Phone p " +
                "JOIN Person pr ON pr.id = p.person_id " +
                "GROUP BY pr.name",
        resultSetMapping = "person_phone_count",
        timeout = 1,
        readOnly = true
    ),
})
@SqlResultSetMapping(
    name = "person_phone_count",
    classes = @ConstructorResult(
        targetClass = PersonPhoneCount.class,
        columns = {
            @ColumnResult(name = "name"),
            @ColumnResult(name = "phoneCount")
        }
    )
)

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation