Search⌘ K
AI Features

Adding Properties to User

Explore how to expand the User entity by adding essential properties such as gender, birthday, email, and phone number. Understand the use of enums, value objects, JPA converters, and validation annotations to integrate these fields properly into the database. Learn to update tests and database migrations to support new user data.

Adding properties to User

So far, our User only has a surrogate primary key (the id). Let’s add some more fields like gender, birthday, email and phone number to make things more interesting:

Java
package com.tamingthymeleaf.application.user;
import io.github.wimdeblauwe.jpearl.AbstractEntity;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;
@Entity
@Table(name = "tt_user")
public class User extends AbstractEntity<UserId> {
@NotNull
private UserName userName; //<.>
@NotNull
@Enumerated(EnumType.STRING)
private Gender gender; //<.>
@NotNull
private LocalDate birthday; //<.>
@NotNull
private Email email; //<.>
@NotNull
private PhoneNumber phoneNumber; //<.>
protected User() {
}
public User(UserId id,
UserName userName,
Gender gender,
LocalDate birthday,
Email email,
PhoneNumber phoneNumber) {
super(id);
this.userName = userName;
this.gender = gender;
this.birthday = birthday;
this.email = email;
this.phoneNumber = phoneNumber;
}
public UserName getUserName() {
return userName;
}
public Gender getGender() {
return gender;
}
public LocalDate getBirthday() {
return birthday;
}
public Email getEmail() {
return email;
}
public PhoneNumber getPhoneNumber() {
return phoneNumber;
}
}
  • UserName is a value object that contains the firstName and lastName of a user.
  • Gender is an enum for the possible genders
...