Skip to lesson

User entity and roles table

ShopLite has customers, but no way for them to sign in: the only login is a temporary development user. Real accounts need a safe home in the database, and a password must never sit there in readable form.

Designing the app_user and user_role tables

app_user is the table with one row per sign-in account: a unique email, the password_hash, an enabled flag and an optional customer_id. A second table, user_role, holds one row per role that account has.

Accounts get their own tables, separate from customers. This is how the three tables relate.

Text
customers (Section 12)        app_user                        user_role---------------------        --------                        ---------customer_id PK  <----------  customer_id FK, UNIQUE, NULLfull_name                    user_id PK       <------------  user_id FKemail UNIQUE                 email UNIQUE                    role 'CUSTOMER' or 'ADMIN'phone                        password_hash                   PRIMARY KEY (user_id, role)created_at                   enabled, created_at
  • email UNIQUE: two accounts can never share a login name (the Duplicate emails lesson shows why this is the real guard)
  • password_hash VARCHAR(255): a BCrypt hash is 60 characters, the {bcrypt} prefix adds 8, and an Argon2 hash needs about 100
  • customer_id UNIQUE and NULL-able: at most one account per customer, none for staff
  • enabled: switch an account off without deleting its order history

A separate table keeps two questions apart: customers says who buys and where to deliver, app_user says who may sign in. An admin signs in but never buys, so an admin has no customer row, and a customer created by an admin may have no account yet.

user_role has its own table because one user can hold several roles, and a CHECK constraint stops typos such as 'ADMN'; a comma-separated roles column would need string splitting in every query. You start from shoplite-api as the Security setup project left it, with one temporary in-memory user; by the end of this module every sign-in is checked against these tables.

The table is not called user: USER is a reserved word in standard SQL and in PostgreSQL, and MySQL has a USER() function. app_user works everywhere without quoting.

A Flyway migration that adds the tables

Flyway migration is a versioned SQL file that Flyway runs once on every database and records in flyway_schema_history, so every copy of the application gets exactly the same tables.

One new versioned file, V4__create_users_and_roles.sql, creates both tables in src/main/resources/db/migration.

Example 1 · src/main/resources/db/migration/V4__create_users_and_roles.sql

Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)

Text
-- Sign-in accounts. A customer account points to its customers row;-- staff accounts (admins) have no customer row, so customer_id may be NULL.CREATE TABLE app_user (  user_id       INT          NOT NULL AUTO_INCREMENT PRIMARY KEY,  email         VARCHAR(255) NOT NULL,  password_hash VARCHAR(255) NOT NULL,  enabled       BOOLEAN      NOT NULL DEFAULT TRUE,  customer_id   INT          NULL,  created_at    DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,  CONSTRAINT uq_app_user_email UNIQUE (email),  CONSTRAINT uq_app_user_customer UNIQUE (customer_id),  CONSTRAINT fk_app_user_customer FOREIGN KEY (customer_id) REFERENCES customers (customer_id));-- One row per role a user has: (7, 'CUSTOMER'), (1, 'ADMIN') ...CREATE TABLE user_role (  user_id INT         NOT NULL,  role    VARCHAR(20) NOT NULL,  PRIMARY KEY (user_id, role),  CONSTRAINT fk_user_role_user FOREIGN KEY (user_id) REFERENCES app_user (user_id) ON DELETE CASCADE,  CONSTRAINT chk_user_role_role CHECK (role IN ('CUSTOMER', 'ADMIN')));
Sample output
$ mvn spring-boot:run
...
INFO  o.f.c.i.s.JdbcTableSchemaHistory : Creating Schema History table `shoplite`.`flyway_schema_history` ...
INFO  o.f.core.internal.command.DbMigrate : Current version of schema `shoplite`: << Empty Schema >>
INFO  o.f.core.internal.command.DbMigrate : Migrating schema `shoplite` to version "1 - create schema"
INFO  o.f.core.internal.command.DbMigrate : Migrating schema `shoplite` to version "2 - index orders customer ordered at"
INFO  o.f.core.internal.command.DbMigrate : Migrating schema `shoplite` to version "3 - index products name"
INFO  o.f.core.internal.command.DbMigrate : Migrating schema `shoplite` to version "4 - create users and roles"
INFO  o.f.core.internal.command.DbMigrate : Successfully applied 4 migrations to schema `shoplite`, now at version v4 (execution time 00:01.581s)
INFO  j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
INFO  com.shoplite.ShopliteApiApplication : Started ShopliteApiApplication in 24.455 seconds (process running for 26.071)

What this code does

  • Flyway finds the new file, sees that the database is at version 3, and runs only V4. On your existing dev database you see just the V4 line; a fresh database (here) runs V1 to V4 in order.
  • uq_app_user_email and uq_app_user_customer are named constraints. When a duplicate arrives, MySQL's error names the constraint, which makes the log easy to read.
  • ON DELETE CASCADE on user_role removes a user's roles together with the user. There is no cascade from customers: deleting a customer who has an account fails, which is what the contract wants (customers are never deleted).

ShopLite already has V1 (the Section 12 tables), V2 and V3 (indexes), so the next free number is V4. Never add the tables to V1: every database that already ran V1 would stop at startup with a checksum mismatch.

MySQL commits each CREATE TABLE on its own, so a typo in the second statement leaves the first table behind and the migration marked as failed. Fix the file, drop the half-made table by hand, run flyway repair and start again. user_role refers to app_user, so it is created second.

The User entity and the Role enum

@ElementCollection marks a collection of simple values, here the enum roles, that JPA stores in a separate table with one row per value, instead of mapping each value as an entity with its own id.

User is the JPA entity for app_user, and Role is a Java enum with CUSTOMER and ADMIN. The roles are an element collection.

Example 2 · src/main/java/com/shoplite/user/User.java: the entity, its roles and the SQL it sends

Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)

Role.javaJava
// src/main/java/com/shoplite/user/Role.javapackage com.shoplite.user;
/** What a ShopLite user may do. Stored by name in user_role.role. */public enum Role {    CUSTOMER,    ADMIN}
// src/main/java/com/shoplite/user/User.javapackage com.shoplite.user;
import java.time.LocalDateTime;import java.util.Collections;import java.util.HashSet;import java.util.Set;
import com.shoplite.customer.Customer;
import jakarta.persistence.CollectionTable;import jakarta.persistence.Column;import jakarta.persistence.ElementCollection;import jakarta.persistence.Entity;import jakarta.persistence.EnumType;import jakarta.persistence.Enumerated;import jakarta.persistence.FetchType;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.JoinColumn;import jakarta.persistence.OneToOne;import jakarta.persistence.Table;
/** A sign-in account. Lives in the service layer only: no controller ever returns it. */@Entity@Table(name = "app_user")public class User {
    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "user_id")    private Integer id;
    @Column(nullable = false, length = 255, unique = true)    private String email;
    @Column(name = "password_hash", nullable = false, length = 255)    private String passwordHash;
    @Column(nullable = false)    private boolean enabled = true;
    @OneToOne(fetch = FetchType.LAZY)    @JoinColumn(name = "customer_id")    private Customer customer;
    @Column(name = "created_at", insertable = false, updatable = false)    private LocalDateTime createdAt;
    @ElementCollection(fetch = FetchType.LAZY)    @CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"))    @Enumerated(EnumType.STRING)    @Column(name = "role", nullable = false, length = 20)    private Set<Role> roles = new HashSet<>();
    protected User() {    }
    public User(String email, String passwordHash, Customer customer, Role role) {        this.email = email;        this.passwordHash = passwordHash;        this.customer = customer;        this.roles.add(role);    }
    public Integer getId() { return id; }    public String getEmail() { return email; }    public String getPasswordHash() { return passwordHash; }    public boolean isEnabled() { return enabled; }    public Customer getCustomer() { return customer; }    public LocalDateTime getCreatedAt() { return createdAt; }    public Set<Role> getRoles() { return Collections.unmodifiableSet(roles); }
    public void disable() {        this.enabled = false;    }
    @Override    public String toString() {        return "User[id=" + id + ", email=" + email + "]";    }}
// src/main/java/com/shoplite/lab/UserMappingLab.javapackage com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Component;
import com.shoplite.user.Role;import com.shoplite.user.User;import com.shoplite.user.UserRepository;
/** Lab only: saves a staff account and prints what was stored. Runs in the "user-lab" profile. */@Component@Profile("user-lab")class UserMappingLab implements CommandLineRunner {
    private final UserRepository users;
    UserMappingLab(UserRepository users) {        this.users = users;    }
    @Override    public void run(String... args) {        User staff = new User("kiran.staff@shoplite.example", "{bcrypt}$2a$10$hash.made.by.the.encoder", null, Role.ADMIN);        users.save(staff);        System.out.println("Saved " + staff + " with roles " + staff.getRoles());    }}
Sample output
$ mvn spring-boot:run -Dspring-boot.run.profiles=dev,user-lab
...
DEBUG org.hibernate.SQL : insert into app_user (customer_id,email,enabled,password_hash) values (?,?,?,?)
DEBUG org.hibernate.SQL : insert into user_role (user_id,role) values (?,?)
Saved User[id=3, email=kiran.staff@shoplite.example] with roles [ADMIN]

What this code does

  • Saving one User sends two INSERTs: the row in app_user, then one row in user_role per role. That is what @ElementCollection with @CollectionTable means.
  • created_at is missing from the INSERT because of insertable = false; MySQL fills it with its DEFAULT. The id 3 comes from AUTO_INCREMENT (the dev data already holds two accounts).
  • toString() prints the id and e-mail only, never the hash. The lab sets a fake hash string; real hashes come from the PasswordEncoder in a later lesson. The lab runs only in the user-lab profile.

Example 3 · Mistake: no @CollectionTable, so Hibernate looks for user_roles

Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)

Java
// User.java with the @CollectionTable line removed@ElementCollection(fetch = FetchType.LAZY)@Enumerated(EnumType.STRING)@Column(name = "role", nullable = false, length = 20)private Set<Role> roles = new HashSet<>();
Sample output
$ mvn spring-boot:run
...
ERROR j.LocalContainerEntityManagerFactoryBean : Failed to initialize JPA EntityManagerFactory: Unable to build Hibernate SessionFactory  [persistence unit: default] ; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: missing table [user_roles]
...
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: missing table [user_roles]

What this code does

  • Without @CollectionTable, JPA invents a table name from the entity and the field: User_roles, which Spring's naming turns into user_roles. The migration created user_role.
  • ddl-auto=validate (Section 16) compares every mapping with the real schema at startup, so the mistake stops the app at once instead of failing at the first sign-in.
  • The fix is to name the table that the migration made. The same check catches a wrong column name or type in @Column.

Three annotations describe the roles table:

  • @CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id")) names the table and its foreign key.
  • @Enumerated(EnumType.STRING) stores the text 'CUSTOMER', not a position number that breaks when someone reorders the enum.
  • @Column(name = "role") names the value column.

The link to the customer is a lazy @OneToOne on customer_id, null for staff. created_at is filled by MySQL, so it is insertable = false, updatable = false. Like every ShopLite entity, User has a protected no-argument constructor for Hibernate and a real constructor for the code.

Fix the error

Fix the user mapping

The app stops at startup or at sign-in. Pick the line that fixes it.

Round 1 of 3

The migration made the table user_role.

@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"))
@Enumerated(EnumType.STRING)
@Column(name = "role", nullable = false, length = 20)
private Set<Role> roles = new HashSet<>();

Error

Schema validation: missing table [user_roles]
User is also the name of a Spring Security class (org.springframework.security.core.userdetails.User). ShopLite never imports that one in the user package, so the short name stays readable; if you ever need both, import one and write the other in full.

A new com.shoplite.user feature package

@EntityGraph is a Spring Data annotation that lists lazy fields to load in the same query. With attributePaths = "roles" the SELECT gets a join, so the roles arrive together with the user.

Package by feature (Section 15) keeps everything about accounts in one package, com.shoplite.user. This is what lives where.

Text
com.shoplite.user  Role.java                    enum CUSTOMER, ADMIN  User.java                    entity for app_user (roles in user_role)  UserRepository.java          findByEmail (with roles), existsByEmail  UserService.java             account rules: sign-up comes in this modulecom.shoplite.customer          Customer, CustomerRepository (Section 16)com.shoplite.common.security   SecurityConfig (previous module)

Example 4 · src/main/java/com/shoplite/user/UserRepository.java: one SELECT with the roles

Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)

UserRepository.javaJava
// src/main/java/com/shoplite/user/UserRepository.javapackage com.shoplite.user;
import java.util.Optional;
import org.springframework.data.jpa.repository.EntityGraph;import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Integer> {
    /** Loads the roles in the same query: sign-in needs them after the transaction has ended. */    @EntityGraph(attributePaths = "roles")    Optional<User> findByEmail(String email);
    boolean existsByEmail(String email);}
// src/main/java/com/shoplite/lab/UserLookupLab.javapackage com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Component;
import com.shoplite.user.User;import com.shoplite.user.UserRepository;
/** Lab only: loads an account by e-mail outside any transaction. Runs in the "lookup-lab" profile. */@Component@Profile("lookup-lab")class UserLookupLab implements CommandLineRunner {
    private final UserRepository users;
    UserLookupLab(UserRepository users) {        this.users = users;    }
    @Override    public void run(String... args) {        User asha = users.findByEmail("asha.rao@example.com").orElseThrow();        System.out.println("Found " + asha);        System.out.println("Roles: " + asha.getRoles() + ", enabled: " + asha.isEnabled());        System.out.println("Customer id: " + asha.getCustomer().getId());        System.out.println("Exists ravi? " + users.existsByEmail("ravi.kumar@example.com"));    }}
Sample output
$ mvn spring-boot:run -Dspring-boot.run.profiles=dev,lookup-lab
...
DEBUG org.hibernate.SQL : select u1_0.user_id,u1_0.created_at,u1_0.customer_id,u1_0.email,u1_0.enabled,u1_0.password_hash,r1_0.user_id,r1_0.role from app_user u1_0 left join user_role r1_0 on u1_0.user_id=r1_0.user_id where u1_0.email=?
Found User[id=2, email=asha.rao@example.com]
Roles: [CUSTOMER], enabled: true
Customer id: 1
DEBUG org.hibernate.SQL : select u1_0.user_id from app_user u1_0 where u1_0.email=? limit ?
Exists ravi? false

Without @EntityGraph on findByEmail:
ERROR o.s.boot.SpringApplication : Application run failed
org.hibernate.LazyInitializationException: Cannot lazily initialize collection of role 'com.shoplite.user.User.roles' with key '2' (no session)

What this code does

  • @EntityGraph(attributePaths = "roles") adds a left join user_role to the SELECT, so the roles arrive with the user. The runner reads them outside any transaction, exactly like the sign-in code will.
  • getCustomer().getId() works without another query: a lazy proxy already knows its id. existsByEmail sends a light select ... limit ?; Ravi is a customer from the seed data but has no account.
  • The last lines are the same runner without the entity graph: the roles were never loaded, the transaction was over, and Hibernate throws LazyInitializationException.

UserRepository extends JpaRepository<User, Integer> with two derived queries, findByEmail and existsByEmail. findByEmail carries @EntityGraph(attributePaths = "roles") because sign-in reads the roles after the repository call has returned, and with open-in-view off no session is left to load them lazily.

Only the service uses the repository, and controllers only see records, which keeps the password hash inside the package. The next lessons add the sign-in adapter, AuthController and the DTOs to the same folder.

The password column holds a hash, never a DTO field

password_hash is the column that stores the output of a slow, salted password hash such as {bcrypt}$2a$10$..., never the password itself. It may travel from the database into the sign-in check, and nowhere else.

The hash stays inside the package. Example 5 shows what happens when a controller returns the entity.

Example 5 · Mistake: returning the entity from a controller

Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)

Java
// LAB ONLY: never add this to ShopLite@RestControllerclass EntityLeakLabController {
    private final UserRepository users;
    EntityLeakLabController(UserRepository users) {        this.users = users;    }
    @GetMapping("/api/v1/lab/users/{email}")    User user(@PathVariable String email) {        return users.findByEmail(email).orElseThrow();      // the entity itself goes to Jackson    }}
Sample output
$ curl -u admin@shoplite.example:shoplite-admin-dev http://localhost:8080/api/v1/lab/users/admin@shoplite.example
{"email":"admin@shoplite.example","passwordHash":"{bcrypt}$2a$10$I8Y8ApR1o0xHK5Pjl.psm.6505DA.Vsi5Ou8ydn8H8yISdoNzUbgS","customer":null,"id":1,"enabled":true,"createdAt":"2026-10-16T13:20:52","roles":["ADMIN"]}

$ curl -u admin@shoplite.example:shoplite-admin-dev http://localhost:8080/api/v1/lab/users/asha.rao@example.com
{"title":"Internal Server Error","status":500,"detail":"Failed to write request","instance":"/api/v1/lab/users/asha.rao@example.com"}

What this code does

  • Jackson writes every getter of the entity, so the admin's passwordHash goes straight to the caller. A copy of this hash is all an attacker needs for an offline guessing attack.
  • For Asha the call fails: customer is a lazy Hibernate proxy and the session is closed, so Jackson cannot write it. One bug, two symptoms, depending on the row.
  • The fix is the ShopLite rule: services return records such as UserResponse (built in the Sign-up lesson), which have no hash field at all.

A leaked hash lets an attacker try millions of guesses on their own machine, with no rate limit and no log entry on your side. So ShopLite never returns the User entity: responses use UserResponse, a record with no password field, and User.toString() leaves the hash out of log lines.

The mistake in Example 5 has two symptoms. The admin's passwordHash goes straight to the caller, and a customer account fails with a 500 because Jackson meets the lazy customer proxy. The PasswordEncoder lesson shows how the hash is made.

Next step

Check your understanding

11 quick questions