Spring Boot MySQL Database Design with Flyway and JPA (Uptime Monitor Part 2)
Design the MySQL schema for a Spring Boot uptime monitor: Flyway migrations, indexes, JPA entities, auditing and optimistic locking. Part 2 of the UpCheck series.
Part 2 of the UpCheck series designs the MySQL schema: four tables created by a Flyway migration, the indexes that keep queries fast, and the JPA entities that map them.
- Part 1: Project setup with MySQL and Docker
- Part 2: Database design with Flyway and JPA (you are here)
- Part 3: REST API, validation and error handling
- Part 4: Spring Security with JWT
- Part 5: Scheduler with virtual threads
- Part 6: Incidents and email alerts
- Part 7: Uptime stats, pagination and retention
- Part 8: Testing, Docker and deployment
MySQL database design with Flyway and JPA entities#
Today you create four tables with a Flyway migration and map them to JPA entities. Good indexes now save you from slow dashboards later.
The four tables#
| Table | One row is | Grows by |
|---|---|---|
| users | an account | sign-ups |
| monitors | a URL to watch | user actions |
| check_results | one HTTP check | every check (largest table) |
| incidents | one period of downtime | each outage |
The monitors table is the hub: one user owns many monitors, and each monitor has many check results and incidents.
Why Flyway instead of ddl-auto=update?#
ddl-auto=update guesses schema changes and never drops or renames anything safely. Flyway runs versioned SQL files in order and records them in flyway_schema_history, so every environment gets the exact same schema. Never edit a migration after it has run; add V2__...sql instead.
Step 1: The migration#
-- src/main/resources/db/migration/V1__create_tables.sql
CREATE TABLE users (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL,
password VARCHAR(100) NOT NULL,
role VARCHAR(20) NOT NULL DEFAULT 'USER',
created_at DATETIME(6) NOT NULL,
updated_at DATETIME(6) NOT NULL,
CONSTRAINT uk_users_email UNIQUE (email)
);
CREATE TABLE monitors (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
owner_id BIGINT NOT NULL,
name VARCHAR(100) NOT NULL,
url VARCHAR(2048) NOT NULL,
interval_minutes INT NOT NULL,
active BOOLEAN NOT NULL DEFAULT TRUE,
status VARCHAR(10) NOT NULL DEFAULT 'UNKNOWN',
consecutive_failures INT NOT NULL DEFAULT 0,
last_checked_at DATETIME(6) NULL,
version BIGINT NOT NULL DEFAULT 0,
created_at DATETIME(6) NOT NULL,
updated_at DATETIME(6) NOT NULL,
CONSTRAINT fk_monitors_owner FOREIGN KEY (owner_id) REFERENCES users (id) ON DELETE CASCADE,
CONSTRAINT chk_monitors_interval CHECK (interval_minutes IN (1, 5, 15))
);
CREATE INDEX idx_monitors_due ON monitors (active, last_checked_at);
CREATE INDEX idx_monitors_owner ON monitors (owner_id);
CREATE TABLE check_results (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
monitor_id BIGINT NOT NULL,
checked_at DATETIME(6) NOT NULL,
up BOOLEAN NOT NULL,
status_code INT NULL,
response_time_ms BIGINT NULL,
error_message VARCHAR(500) NULL,
CONSTRAINT fk_checks_monitor FOREIGN KEY (monitor_id) REFERENCES monitors (id) ON DELETE CASCADE
);
CREATE INDEX idx_checks_monitor_time ON check_results (monitor_id, checked_at);
CREATE INDEX idx_checks_time ON check_results (checked_at);
CREATE TABLE incidents (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
monitor_id BIGINT NOT NULL,
started_at DATETIME(6) NOT NULL,
resolved_at DATETIME(6) NULL,
cause VARCHAR(500) NULL,
CONSTRAINT fk_incidents_monitor FOREIGN KEY (monitor_id) REFERENCES monitors (id) ON DELETE CASCADE
);
CREATE INDEX idx_incidents_monitor_open ON incidents (monitor_id, resolved_at);
Each index has one job:
idx_monitors_duelets the scheduler find due monitors without scanning the table.idx_checks_monitor_timepowers the history page and the uptime % query (monitor + time range).idx_checks_timemakes the nightly cleanup delete fast.ON DELETE CASCADEmeans deleting a monitor removes its checks and incidents in one SQL statement.
Step 2: A base class for id and audit columns#
package com.upcheck.common;
import jakarta.persistence.*;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.time.Instant;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@CreatedDate
@Column(name = "created_at", nullable = false, updatable = false)
private Instant createdAt;
@LastModifiedDate
@Column(name = "updated_at", nullable = false)
private Instant updatedAt;
public Long getId() { return id; }
public Instant getCreatedAt() { return createdAt; }
public Instant getUpdatedAt() { return updatedAt; }
}
Step 3: The User entity#
package com.upcheck.user;
import com.upcheck.common.BaseEntity;
import jakarta.persistence.*;
@Entity
@Table(name = "users")
public class User extends BaseEntity {
@Column(nullable = false, length = 100)
private String name;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false, length = 100)
private String password; // BCrypt hash, never the raw password
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 20)
private Role role = Role.USER;
protected User() {} // for JPA
public User(String name, String email, String passwordHash) {
this.name = name;
this.email = email;
this.password = passwordHash;
}
public String getName() { return name; }
public String getEmail() { return email; }
public String getPassword() { return password; }
public Role getRole() { return role; }
public enum Role { USER, ADMIN }
}
package com.upcheck.user;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
boolean existsByEmail(String email);
}
Step 4: The Monitor entity (with its business rule inside)#
The status logic lives in the entity, not in a service. That keeps the rule in one place and makes it trivial to unit test. Note @Version: it stops a user edit and a background check from silently overwriting each other.
package com.upcheck.monitor;
public enum MonitorStatus {
UNKNOWN, // never checked yet
UP,
DOWN
}
package com.upcheck.monitor;
import com.upcheck.common.BaseEntity;
import com.upcheck.user.User;
import jakarta.persistence.*;
import java.time.Instant;
@Entity
@Table(name = "monitors")
public class Monitor extends BaseEntity {
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "owner_id", nullable = false)
private User owner;
@Column(nullable = false, length = 100)
private String name;
@Column(nullable = false, length = 2048)
private String url;
@Column(name = "interval_minutes", nullable = false)
private int intervalMinutes;
@Column(nullable = false)
private boolean active = true;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 10)
private MonitorStatus status = MonitorStatus.UNKNOWN;
@Column(name = "consecutive_failures", nullable = false)
private int consecutiveFailures;
@Column(name = "last_checked_at")
private Instant lastCheckedAt;
@Version
private long version;
protected Monitor() {}
public Monitor(User owner, String name, String url, int intervalMinutes) {
this.owner = owner;
this.name = name;
this.url = url;
this.intervalMinutes = intervalMinutes;
}
public void update(String name, String url, int intervalMinutes, boolean active) {
boolean urlChanged = !this.url.equals(url);
this.name = name;
this.url = url;
this.intervalMinutes = intervalMinutes;
this.active = active;
if (urlChanged) {
// check the new URL on the next poll; status stays as-is so an open
// incident is closed (and a RECOVERED email sent) once the new URL is UP
this.consecutiveFailures = 0;
this.lastCheckedAt = null;
}
}
/**
* Applies one check result and returns the new status when it changed, else null.
* A site is DOWN only after failureThreshold failures in a row,
* so one slow response doesn't wake anyone up at 3 a.m.
*/
public MonitorStatus recordCheck(boolean up, Instant checkedAt, int failureThreshold) {
this.lastCheckedAt = checkedAt;
MonitorStatus previous = this.status;
if (up) {
consecutiveFailures = 0;
status = MonitorStatus.UP;
} else {
consecutiveFailures++;
if (consecutiveFailures >= failureThreshold) {
status = MonitorStatus.DOWN;
}
}
return previous != status ? status : null;
}
public User getOwner() { return owner; }
public String getName() { return name; }
public String getUrl() { return url; }
public int getIntervalMinutes() { return intervalMinutes; }
public boolean isActive() { return active; }
public MonitorStatus getStatus() { return status; }
public int getConsecutiveFailures() { return consecutiveFailures; }
public Instant getLastCheckedAt() { return lastCheckedAt; }
}
Step 5: CheckResult and Incident entities#
CheckOutcome is a plain record for the result of one HTTP call. The entity copies it when we save.
package com.upcheck.check;
import java.time.Instant;
public record CheckOutcome(boolean up, Integer statusCode, Long responseTimeMs,
String errorMessage, Instant checkedAt) {
private static final int MAX_ERROR_LENGTH = 500;
public static CheckOutcome success(int statusCode, long responseTimeMs, Instant at) {
return new CheckOutcome(true, statusCode, responseTimeMs, null, at);
}
public static CheckOutcome httpFailure(int statusCode, long responseTimeMs, Instant at) {
return new CheckOutcome(false, statusCode, responseTimeMs, "HTTP " + statusCode, at);
}
public static CheckOutcome error(String message, Long responseTimeMs, Instant at) {
String safe = message == null ? "Unknown error" : message;
if (safe.length() > MAX_ERROR_LENGTH) {
safe = safe.substring(0, MAX_ERROR_LENGTH);
}
return new CheckOutcome(false, null, responseTimeMs, safe, at);
}
}
package com.upcheck.check;
import com.upcheck.monitor.Monitor;
import jakarta.persistence.*;
import java.time.Instant;
/** One row per check. Append-only, so no audit columns. */
@Entity
@Table(name = "check_results")
public class CheckResult {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "monitor_id", nullable = false)
private Monitor monitor;
@Column(name = "checked_at", nullable = false)
private Instant checkedAt;
@Column(nullable = false)
private boolean up;
@Column(name = "status_code")
private Integer statusCode;
@Column(name = "response_time_ms")
private Long responseTimeMs;
@Column(name = "error_message", length = 500)
private String errorMessage;
protected CheckResult() {}
public CheckResult(Monitor monitor, CheckOutcome outcome) {
this.monitor = monitor;
this.checkedAt = outcome.checkedAt();
this.up = outcome.up();
this.statusCode = outcome.statusCode();
this.responseTimeMs = outcome.responseTimeMs();
this.errorMessage = outcome.errorMessage();
}
public Long getId() { return id; }
public Monitor getMonitor() { return monitor; }
public Instant getCheckedAt() { return checkedAt; }
public boolean isUp() { return up; }
public Integer getStatusCode() { return statusCode; }
public Long getResponseTimeMs() { return responseTimeMs; }
public String getErrorMessage() { return errorMessage; }
}
package com.upcheck.incident;
import com.upcheck.monitor.Monitor;
import jakarta.persistence.*;
import java.time.Duration;
import java.time.Instant;
/** A period of downtime: opens when a monitor goes DOWN, closes when it is UP again. */
@Entity
@Table(name = "incidents")
public class Incident {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "monitor_id", nullable = false)
private Monitor monitor;
@Column(name = "started_at", nullable = false)
private Instant startedAt;
@Column(name = "resolved_at")
private Instant resolvedAt;
@Column(length = 500)
private String cause;
protected Incident() {}
public Incident(Monitor monitor, Instant startedAt, String cause) {
this.monitor = monitor;
this.startedAt = startedAt;
this.cause = cause;
}
public void resolve(Instant at) { this.resolvedAt = at; }
public boolean isOpen() { return resolvedAt == null; }
public Duration duration(Instant now) {
return Duration.between(startedAt, resolvedAt != null ? resolvedAt : now);
}
public Long getId() { return id; }
public Monitor getMonitor() { return monitor; }
public Instant getStartedAt() { return startedAt; }
public Instant getResolvedAt() { return resolvedAt; }
public String getCause() { return cause; }
}
Restart the app. Flyway logs Successfully applied 1 migration, and Hibernate validates all four entities against the tables. If a column name or type does not match, startup fails with a clear message, which is exactly why validate is the safe choice.
Key takeaways#
- Flyway runs versioned SQL so every environment has the same schema; Hibernate only validates it.
- Design indexes for your real queries: due monitors, history by time and nightly cleanup.
- Put business rules like UP/DOWN transitions in the entity and guard it with @Version.