Skip to lesson

Practice: persistence context and lifecycle

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Four mistakes cause most persistence-context bugs in Spring Data JPA code: a change to an unmanaged entity, an ignored merge result, a late constraint error and an entity that leaves its transaction. Each comes with its real log and fix.

Mistake 1: changing an entity that is not managed

A service method without @Transactional loads an entity and changes it. The listing shows that the change disappears without an error.

Example 1 · Mistake: a phone number change without a transaction

Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)

CustomerPhoneService.javaJava
// src/main/java/com/shoplite/lab/CustomerPhoneService.javapackage com.shoplite.lab;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.customer.Customer;import com.shoplite.customer.CustomerRepository;
@Servicepublic class CustomerPhoneService {
    private final CustomerRepository customers;
    public CustomerPhoneService(CustomerRepository customers) {        this.customers = customers;    }
    // Mistake: no transaction, so the customer is detached when the phone changes    public void updatePhoneBroken(int id, String phone) {        Customer customer = customers.findById(id).orElseThrow();        customer.setPhone(phone);    }
    @Transactional    public void updatePhone(int id, String phone) {        Customer customer = customers.findById(id).orElseThrow();        customer.setPhone(phone);    }
    @Transactional(readOnly = true)    public String phoneOf(int id) {        return customers.findById(id).orElseThrow().getPhone();    }}
// src/main/java/com/shoplite/lab/PhoneUpdateDemo.java (its run method)@Overridepublic void run() {    service.updatePhoneBroken(6, "9876543206");    System.out.println("after updatePhoneBroken: " + service.phoneOf(6));    service.updatePhone(6, "9876543206");    System.out.println("after updatePhone:       " + service.phoneOf(6));}
Sample output
$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=phone-update"
DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
after updatePhoneBroken: null
DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
DEBUG org.hibernate.SQL : update customers set email=?,full_name=?,phone=? where customer_id=?
DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
after updatePhone:       9876543206

What this code does

  • updatePhoneBroken has no @Transactional: findById returns a detached customer, the setter changes only memory, and Arjun's phone is still null when read back. No UPDATE appears in the log.
  • updatePhone loads and changes in one transaction, so the UPDATE is sent at commit and the new number is stored.

A change reaches the database only if the entity is managed when the transaction commits. The method without @Transactional loads the entity in a short transaction of its own, so the setter runs on a detached object.

The check to make: is there one transaction around both the load and the change? If yes, dirty checking writes it. If no, nothing does, and calling save() "to be safe" only hides the problem in some places while leaving it in others.

Mistake 2: ignoring what merge (and save) returns

A detached category is saved, and then the old reference is changed. The listing shows that the change goes to an object nothing tracks.

Example 2 · Mistake: the result of save() is thrown away

Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// src/main/java/com/shoplite/lab/MergeIgnoredDemo.java (its run method)@Overridepublic void run() {    Product shoes = products.findById(13).orElseThrow();       // detached after this line    tx.executeWithoutResult(status -> {        products.save(shoes);                                   // merge: the result is thrown away        shoes.setPrice(new BigDecimal("2299.00"));    });    System.out.println("price now: " + products.findById(13).orElseThrow().getPrice());}
Sample output
$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=merge-ignored"
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
price now: 2499.00

What this code does

  • products.save(shoes) merged the detached object: the second SELECT is merge loading the row. The managed copy it returned was ignored.
  • shoes.setPrice(...) changed the detached object, which no persistence context tracks, so no UPDATE was sent and the price is still 2499.00. Practice 5 fixes the same mistake for a category.

save(detached) calls merge, which returns a different, managed object. The fix is one assignment: Category managed = categories.save(kitchen); and from then on only managed.

The bigger fix is to avoid merging detached copies at all: load inside the transaction and change only what the request asks for.

Mistake 3: expecting database errors at save()

A category with a duplicate name is renamed. The listing shows that the error appears only at commit.

Example 3 · Mistake: a duplicate name found only at commit

Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// src/main/java/com/shoplite/lab/CategoryAdminService.java (the rename method)@Transactionalpublic String rename(int id, String newName) {    Category category = categories.findById(id).orElseThrow();    category.setName(newName);    return category.getName();}
// src/main/java/com/shoplite/lab/RenameAtCommitDemo.java (its run method)@Overridepublic void run() {    try {        String name = admin.rename(6, "Books");          // Fashion -> Books: the name is taken        System.out.println("rename() returned " + name);    } catch (DataIntegrityViolationException e) {        System.out.println("caller got " + e.getClass().getSimpleName() + " after rename() returned");    }}
Sample output
$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=rename-at-commit"
DEBUG org.hibernate.SQL : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
DEBUG org.hibernate.SQL : update categories set name=?,parent_id=? where category_id=?
WARN  org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 1062, SQLState: 23000
WARN  org.hibernate.orm.jdbc.error : Duplicate entry 'Books' for key 'categories.uq_categories_name'
caller got DataIntegrityViolationException after rename() returned

What this code does

  • Renaming Fashion to Books breaks uq_categories_name, but rename itself finished: the UPDATE ran at commit, after the method's last line.
  • The caller receives DataIntegrityViolationException with no chance for the service to say "409 already-exists". renameOrConflict in the Save vs persist lesson fixes it with saveAndFlush.

UPDATEs wait for the flush, so a UNIQUE or CHECK violation surfaces at commit, after the service method has returned. The caller then gets a raw DataIntegrityViolationException that no service code could turn into a 409.

Where the error matters, flush on purpose (flush() or saveAndFlush) inside the method, catch DataIntegrityViolationException there and throw a meaningful exception. Do not catch it and carry on: the transaction is already marked for rollback.

Mistake 4: letting an entity leave the transaction

A read-only service returns an entity, and the caller reads a lazy collection. The listing shows the exception.

Example 4 · Mistake: the caller reads a lazy collection

Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)

AddressBookService.javaJava
// src/main/java/com/shoplite/lab/AddressBookService.javapackage com.shoplite.lab;
import java.util.List;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.customer.Customer;import com.shoplite.customer.CustomerRepository;
@Servicepublic class AddressBookService {
    private final CustomerRepository customers;
    public AddressBookService(CustomerRepository customers) {        this.customers = customers;    }
    // Mistake: returns the entity; the addresses were never loaded    @Transactional(readOnly = true)    public Customer find(int id) {        return customers.findById(id).orElseThrow();    }
    @Transactional(readOnly = true)    public List<String> labels(int id) {        return customers.findById(id).orElseThrow().getAddresses().stream()                .map(address -> address.getLabel() + ", " + address.getPostalAddress().city())                .toList();    }}
// src/main/java/com/shoplite/lab/AddressesLieDemo.java (its run method)@Overridepublic void run() {    Customer priya = service.find(5);    try {        priya.getAddresses().forEach(a -> System.out.println(a.getLabel()));    } catch (RuntimeException e) {        System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());    }    System.out.println("fixed: " + service.labels(5));}
Sample output
$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=addresses-lie"
DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
LazyInitializationException: Cannot lazily initialize collection of role 'com.shoplite.customer.Customer.addresses' with key '5' (no session)
DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
DEBUG org.hibernate.SQL : select a1_0.customer_id,a1_0.address_id,a1_0.is_default,a1_0.label,a1_0.line1,a1_0.city,a1_0.state,a1_0.pincode from addresses a1_0 where a1_0.customer_id=?
fixed: [Hostel, Pune, Home, Pune]

What this code does

  • find(5) returned Priya's customer entity; her addresses were never loaded and the session closed on return, so the loop fails with LazyInitializationException.
  • labels(5) reads the addresses inside its read-only transaction (one more SELECT) and returns plain strings: the caller needs no database access.

A read-only service that returns an entity looks fine until the caller touches a lazy link. Collections fail with "Cannot lazily initialize collection of role ..." and proxies with "Could not initialize proxy [...] - no session".

Read everything the caller needs inside the transaction and return a DTO, using a fetch join or @EntityGraph when the use case needs linked data. Never fix it with EAGER, open-in-view or enable_lazy_load_no_trans.

Finish up

Mark complete & continue

Next: ShopLite: updates with dirty checking