Edit User Data

Learn how to enable the editing of user data.

Adding version

In order to support the editing of our User entities, we will need to make some changes in the Java code. First of all, we will use io.github.wimdeblauwe.jpearl.AbstractVersionedEntity as the superclass of User instead of io.github.wimdeblauwe.jpearl.AbstractEntity.

This class adds a version field to the entity, which will allow us to use Optimistic LockingA strategy where we take note of the version number while reading a record. This is done to ensure that the version hasn’t changed before we write the record back.. Most importantly, this will guard the user from concurrent updates (either by another user or by himself in another tab, for example).

Updating SQL script

Let’s update our SQL creation script to have the new version field:

Press + to interact
CREATE TABLE tt_user
(
id UUID NOT NULL,
version BIGINT NOT NULL,
first_name VARCHAR NOT NULL,
last_name VARCHAR NOT NULL,
gender VARCHAR NOT NULL,
birthday DATE NOT NULL,
email VARCHAR NOT NULL,
phone_number VARCHAR NOT NULL,
PRIMARY KEY (id)
);

On line 4, we have added the version field.

Edit user method

Next, we’ll create a new UserService method to allow user properties to be eidted:

Press + to interact
User editUser(UserId userId, EditUserParameters parameters);

Since we will allow the editing of all parameters used at creation, we can extend from CreateUserParameters and add the version field:

Press + to interact
package com.tamingthymeleaf.application.user;
import java.time.LocalDate;
public class EditUserParameters extends CreateUserParameters {
private final long version;
public EditUserParameters(long version, UserName userName, Gender gender, LocalDate birthday, Email email, PhoneNumber phoneNumber) {
super(userName, gender, birthday, email, phoneNumber);
this.version = version;
}
public long getVersion() {
return version;
}
}

Now we’ll update UserServiceImpl by adding the following code:

Press + to interact
@Override
public User editUser(UserId userId, EditUserParameters parameters) {
User user = repository.findById(userId)
.orElseThrow(() -> new UserNotFoundException(userId));
if (parameters.getVersion() != user.getVersion()) {
throw new ObjectOptimisticLockingFailureException(User.class, user.getId().asString());
}
parameters.update(user);
return user;
}
  • Get the user for the given UserId from the database. If
...