Video in progress

Strong Middle 🐻 Hibernate and JPA

If you call a Spring Data repository method from a service without `@Transactional`, what happens with the transaction and the persistence context?

The SimpleJpaRepository methods themselves carry @Transactional (reads are readOnly), so each call runs in its own short transaction. As a result, entities become detached between consecutive calls, changes aren't saved automatically, and lazy associations fail.

📖 Answer

public void rename(Long id, String name) {           // no @Transactional
    User u = userRepo.findById(id).orElseThrow();    // transaction 1, finished
    u.setName(name);                                  // u is now detached
    // if save() isn't called, nothing is saved
    u.getRoles().size();                              // LazyInitializationException
}

Every repository method opens and closes its own transaction. Dirty checking doesn't work, because the persistence context that tracks the entity is already closed. If you call userRepo.save(u), it does a merge(): another SELECT and then an UPDATE.

If you have several writes, they aren't atomic:

orderRepo.save(order);       // commit
paymentRepo.save(payment);   // an error here -> the order is saved anyway

open-in-view=true (the Spring Boot default) muddies this picture a bit: one EntityManager stays open for the whole HTTP request, so lazy loading works, but the transaction is still separate for each method. The bug stays invisible and then suddenly shows up in a background job (where there's no OSIV).

My rule is simple: I wrap a business operation in one @Transactional at the service level. The repository's own transactions are enough only for "single query" cases.