ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Spring-boot读书笔记一The persistence context

2026/8/12 16:00:24 拓冰建站 浏览量
Spring-boot读书笔记一The persistence context

The persistence context is a key JPA concept that acts as a first-level cache and entity lifecycle manager. Here are its details:

What it is:

  • A runtime environment where entity instances are managed
  • A cache that holds entity objects between the database and your application
  • Managed by the EntityManager

Key characteristics:
Entity States:

  • Transient - New objects not yet persisted
  • Managed - Objects tracked by the persistence context
  • Detached - Previously managed objects no longer tracked
  • Removed - Marked for deletion

Scope in the test:

  • Transaction-scoped - Lives for the duration of a transaction
  • Automatic dirty checking - Tracks changes to managed entities
  • Identity guarantee - Same entity ID returns same object instance

In the code context:

// Entities become managed when saved via repository
courseRepository.saveAll(getCourseList());// EntityManager operates within the same persistence context
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

Benefits:

  • Performance - Avoids repeated database queries for same entity
  • Consistency - Ensures object identity within transaction
  • Change tracking - Automatically detects and persists modifications
  • Lazy loading - Loads related entities on-demand

Lifecycle:

  • Created when transaction starts
  • Destroyed when transaction commits/rolls back
  • All changes flushed to database at transaction boundary

In Spring Boot tests with @SpringBootTest, each test method typically runs in its own transaction, creating a fresh persistence context