Skip to content

Commit d48054a

Browse files
Intercept the generated SQL for logging or altering
1 parent 95e1742 commit d48054a

File tree

1 file changed

+4
-14
lines changed

1 file changed

+4
-14
lines changed

HibernateSpringBootInterceptSql/README.md

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,10 @@
1-
**[How To Avoid `LazyInitializationException` Via `JOIN FETCH`](https://github.com/AnghelLeonard/Hibernate-SpringBoot/tree/master/HibernateSpringBootJoinFetch)**
1+
**[How To Intercept The Generated SQL For Logging Or Altering](https://github.com/AnghelLeonard/Hibernate-SpringBoot/tree/master/HibernateSpringBootInterceptSql)**
22

3-
**See also:**
4-
- [LEFT JOIN FETCH](https://github.com/AnghelLeonard/Hibernate-SpringBoot/tree/master/HibernateSpringBootLeftJoinFetch)
5-
- [JOIN VS. JOIN FETCH](https://github.com/AnghelLeonard/Hibernate-SpringBoot/tree/master/HibernateSpringBootJoinVSJoinFetch)
6-
7-
**Description:** Typically, when we get a `LazyInitializationException` we tend to modify the association fetching type from `LAZY` to `EAGER`. That is very bad! This is a [code smell](https://vladmihalcea.com/eager-fetching-is-a-code-smell/). Best way to avoid this exception is to rely on `JOIN FETCH` (if you plan to modify the fetched entities) or `JOIN` + DTO (if the fetched data is only read). `JOIN FETCH` allows associations to be initialized along with their parent objects using a single `SELECT`. This is particularly useful for fetching associated collections.
8-
9-
This application is a `JOIN FETCH` example for avoiding `LazyInitializationException`.
3+
**Description:** Sometimes we need to intercept the generated SQL that originates from Spring Data, `EntityManager`, Criteria API, `JdbcTemplate` and so on. This can be done as in this sample application. After interception, you can log, modify or even return a brand new SQL that will be executed in the end.
104

115
**Key points:**
12-
- define two related entities (e.g., `Author` and `Book` in a `@OneToMany` lazy-bidirectional association)
13-
- write a JPQL `JOIN FETCH` to fetch an author including his books
14-
- write a JPQL `JOIN FETCH` (or `JOIN`) to fetch a book including its author
15-
16-
**Output example:**\
17-
![](https://github.com/AnghelLeonard/Hibernate-SpringBoot/blob/master/HibernateSpringBootJoinFetch/hibernate%20spring%20boot%20join%20fetch.png)
6+
- define an implementation of Hibernate `StatementInspector` SPI
7+
- configure this SPI in `application.properties` via `spring.jpa.properties.hibernate.session_factory.statement_inspector`
188

199
-----------------------------------------------------------------------------------------------------------------------
2010
<table>

0 commit comments

Comments
 (0)