new doc section on slow queries and SQL comments

This commit is contained in:
Gavin King 2023-07-07 11:07:58 +02:00 committed by Christian Beikov
parent 8fd02b42d1
commit 43264d225a
2 changed files with 32 additions and 11 deletions

View File

@ -619,20 +619,16 @@ It might return a single `Book`.
[source,java]
----
interface Queries {
@HQL("from Book where isbn = :isbn")
Book findBookByIsbn(String isbn);
}
----
It might even return `TypedQuery` or `SelectionQuery`:
[source,java]
----
interface Queries {
@HQL("from Book where title like :title")
SelectionQuery<Book> findBooksByTitle(String title);
}
----
This is extremely useful at times, since it allows the client to further manipulate the query:
@ -641,9 +637,12 @@ This is extremely useful at times, since it allows the client to further manipul
----
List<Book> books =
Queries_.findBooksByTitle(entityManager, titlePattern)
.ascending(Book_.title) // order the results
.setMaxResults(RESULTS_PER_PAGE) // return at most 20 results
.setFirstResult(page*RESULTS_PER_PAGE) // start from the given page of results
.setOrder(Order.asc(Book_.title)) // order the results
.setPage(Page.page(RESULTS_PER_PAGE, page)) // return the given page of results
.setFlushMode(FlushModeType.COMMIT) // don't flush session before query execution
.setReadOnly(true) // load the entities in read-only mode
.setCacheStoreMode(CacheStoreMode.BYPASS) // don't cache the results
.setComment("Hello world!") // add a comment to the generated SQL
.getResultList();
----

View File

@ -980,6 +980,28 @@ long publisherCacheMissCount =
Hibernate's statistics enable observability.
Both {micrometer}[Micrometer] and {smallrye-metrics}[SmallRye Metrics] are capable of exposing these metrics.
[[slow-queries]]
=== Tracking down slow queries
When a poorly-performing SQL query is discovered in production, it can sometimes be hard to track down exactly where in the Java code the query originates.
Hibernate offers two configuration properties that can make it easier to identify a slow query and find its source.
.Settings for tracking slow queries
[%breakable,cols="25,~,~"]
|===
| Configuration property name | Purpose | Property value
| `hibernate.log_slow_query` | Log slow queries at the `INFO` level | The minimum execution time, in milliseconds, which characterizes a "slow" query
| `hibernate.use_sql_comments` | Prepend comments to the executed SQL | `true` or `false`
|===
When `hibernate.use_sql_comments` is enabled, the text of the HQL query is prepended as a comment to the generated SQL, which usually makes it easy to find the HQL in the Java code.
The comment text may be customized:
- by calling `Query.setComment(comment)` or `Query.setHint(AvailableHints.HINT_COMMENT,comment)`, or
- via the `@NamedQuery` annotation.
[[hibernate-reactive]]
=== Reactive programming with Hibernate