| Ko

JPA dirty checking

Load an entity, call a setter, end the transaction, and the row in the database changes. No save(), no update(). The mechanism behind that automatic UPDATE is dirty checking. The core of it is how Hibernate knows which fields changed and what it compares against. The snapshot The baseline for the comparison is the snapshot. The moment an entity enters the persistence context, Hibernate copies all of its field values and stores them separately. That copy is the initial state that matches the database. Internally it’s keyed by the entity identifier, with an Object array holding each field value in order as the value. ...

June 8, 2024 · 5 min · 967 words · In-Jun

The JPA N+1 query problem

You fetch a list of members once, then look at the SQL log and find 101 SELECT lines. That’s the N+1 problem. One initial query to fetch the entities, plus N more, one each time you touch the association, for a total of N+1. The signal here isn’t an estimated millisecond count; it’s the number of queries in the log. How one becomes 101 Say Member references Team with lazy loading (FetchType.LAZY). You fetch 100 members and print each one’s team name in a loop. ...

June 8, 2024 · 5 min · 885 words · In-Jun

Spring Data JPA vs JPA

JPA is the standard API. Spring Data JPA is a code-generation layer on top of it: you declare an interface, it generates the implementation, and that implementation calls the EntityManager underneath. Writing the same operation both ways makes the boundary clear. JPA The center of JPA is the persistence context and the EntityManager that manages it. The persistence context is a logical space that holds entities and provides the first-level cache, dirty checking, lazy loading, and write-behind. In plain JPA, you hold the EntityManager and open and close the transaction yourself. ...

June 7, 2024 · 5 min · 853 words · In-Jun
[email protected]