Spring Data JPA
Entity Update
Java
Programming
Database Management

How to update an entity with Spring Data JPA

Codemia Knowledge Hub ·

Fetch the entity through its repository, change the fields you need, and call save(). You need an entity instance that was either loaded from the database or rebuilt with a known ID; once you modify its attributes, saving persists the changes.

The flow has three steps:

  1. Fetch the entity with the repository, for example findById(id).
  2. Update the entity by calling its setters.
  3. Save the entity back to the database with save(entity).

Example: updating a user's email

Given a User entity with id, name and email, this service updates the email:

java
1@Entity
2public class User {
3    @Id
4    @GeneratedValue(strategy = GenerationType.IDENTITY)
5    private Long id;
6    
7    private String name;
8    private String email;
9
10    // Getters and Setters
11}
12
13public interface UserRepository extends JpaRepository<User, Long> {
14}
15
16@Service
17public class UserService {
18    
19    @Autowired
20    private UserRepository userRepository;
21
22    public User updateUserEmail(Long userId, String newEmail) {
23        User user = userRepository.findById(userId).orElseThrow(() -> new EntityNotFoundException("User not found"));
24        user.setEmail(newEmail);
25        return userRepository.save(user);
26    }
27}

If the user does not exist, orElseThrow raises an EntityNotFoundException. Handle that exception where the update is called.

Running the update in a transaction

Put @Transactional on service methods that update entities so the database work runs inside a transaction. That protects data integrity and lets Spring roll back on failure.

java
1@Transactional
2public User updateUserEmail(Long userId, String newEmail) {
3    // Method body remains the same
4}

Preventing lost updates with @Version

For concurrent updates, add a version field annotated with @Version. JPA increments it on every update, which gives you optimistic locking and prevents one writer from silently overwriting another.

java
1@Entity
2public class User {
3    @Id
4    @GeneratedValue(strategy = GenerationType.IDENTITY)
5    private Long id;
6
7    private String name;
8    private String email;
9
10    @Version
11    private Long version;
12
13    // Getters and Setters
14}

Updating only changed columns with @DynamicUpdate

On entities with many fields, Hibernate's @DynamicUpdate annotation (compatible with Spring Data JPA) makes the generated SQL UPDATE include only the modified columns.

When to skip loading the entity

  • Partial updates: If only a few fields change, a @Query with an update statement avoids the overhead of fetching the full entity.
  • Validation: Validate the entity or the updated fields before saving to avoid data integrity problems.
AspectDescriptionExample/Keyword
Entity RetrievalFetch existing entity from database via repository.findById(id)
Entity ModificationUpdate attributes of the entity.entity.setField(val)
Save ChangesPersist changes back to the database.save(entity)
Transaction HandlingEnsure method executes within a transaction.@Transactional
Concurrency ControlPrevent overwriting updates in concurrent settings.@Version
Optimized UpdatingOnly update changed fields in SQL.@DynamicUpdate

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design