Lesson 20 / 38

JPA & Hibernate

Map Java objects to database tables with JPA entities and Hibernate, understand the persistence context, and spot and fix the N+1 select problem.

Entities & the persistence context

@Entity classes map to tables; the EntityManager's persistence context tracks loaded entities and flushes changes automatically inside a transaction. JPA is the spec, Hibernate the common implementation.

@Entity
class Book {
    @Id @GeneratedValue Long id;
    String title;
    @ManyToOne Author author;
}

interface BookRepository extends JpaRepository<Book, Long> {
    List<Book> findByAuthorName(String name);
}

The N+1 select problem

Lazily loading a collection for each of N parent rows fires N extra queries. Fix with a JOIN FETCH query, an entity graph, or batch fetching. Always check the SQL your ORM actually emits.