Video in progress

After the method below is called, does the user's name change in the database?

@Service
public class UserService {
    private final UserRepository repo;

    @Transactional
    public void rename(Long id, String newName) {
        User user = repo.findById(id).orElseThrow();
        user.setName(newName);
    }
}

Yes, it does. The entity was loaded inside the transaction, so it is managed, and dirty checking finds the change before commit and sends the UPDATE itself. save() isn't needed.

📖 Answer

The sequence goes like this:

  1. @Transactional opens a transaction and a persistence context.
  2. findById sends a SELECT, user becomes managed, and its snapshot is saved.
  3. setName only changes the Java object.
  4. When the method ends, Spring commits; before the commit Hibernate flushes, compares with the snapshot, and sends update users set ... where id=?.

There are cases where the answer is "no", and it's good to mention them in an interview:

  • if @Transactional doesn't kick in: the method is private, or it is called as this.rename(...) from within the same class. The proxy is bypassed, the entity is loaded without a transaction and ends up detached;
  • if it's @Transactional(readOnly = true), Hibernate doesn't flush;
  • if an exception is thrown inside the method and the transaction rolls back;
  • if the name field is @Column(updatable = false).

In practice, not knowing this behavior also causes bugs like "why did something I never saved get written to the database?", for example when someone changes an entity's field for convenience before turning it into a DTO.