Edit User Data
Learn how to enable the editing of user data.
We'll cover the following...
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 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:
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:
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:
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:
@Overridepublic 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