Robust Data Management: Validation and Migrations
8 min read
When building an enterprise Spring Boot application, managing data effectively is half the battle. If your application blindly accepts any data the user throws at it, and if your team has no organized way to manage database schema changes, your server will quickly turn into the Wild West.
In this guide, we will tackle two fundamental industry practices: enforcing strict rules on incoming data (Validation) and safely evolving your database schema over time (Migrations).
1. Validating Incoming Data: jakarta.validation and the @Valid Annotation 🛡️
Definition: Data validation is the process of ensuring that incoming data meets a set of predefined rules before the application attempts to process it.
The Problem: Users are delightfully unpredictable. If your application asks for a user's age, someone will inevitably type "-42". If you ask for an email, someone will submit "i_like_pizza". If your core business logic receives this garbage data, it leads to database exceptions, corrupted application states, or security vulnerabilities (like the infamous "Little Bobby Tables" SQL injection).
If you try to solve this by writing manual conditional checks (if (user.getAge() < 0) { ... }) for every single field across every single incoming request, your controllers will become thousands of lines long and impossible to maintain.
The Solution: Instead of manual if-else blocks, Spring Boot uses Bean Validation (jakarta.validation). You declare rules directly on your Data Transfer Objects (DTOs) using annotations, and Spring enforces them automatically.
Real-Life Scenario: Imagine a bouncer at an exclusive club. Instead of the bartender stopping making drinks to check IDs (your core business logic), the bouncer (validation layer) checks IDs at the door. If a patron doesn't meet the criteria, they are immediately turned away before they even step inside.
Setup and Boilerplate (Spring Boot 3.x)
In Spring Boot 3.x, the Java ecosystem migrated from the javax.* namespace to the jakarta.* namespace. To enable validation, you must add the standard Spring Boot starter dependency to your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>The @Valid Annotation
To tell Spring to actively enforce the rules you've set on an object, you place the @Valid annotation next to your @RequestBody in the controller.
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping
public String createUser(@Valid @RequestBody UserDto userDto) {
// If the data is invalid, Spring intercepts the request BEFORE it reaches this line.
// We only arrive here if the data is 100% clean.
return "User created successfully!";
}
}Under the hood: When a request arrives, Spring intercepts it, spots the @Valid annotation, and passes the payload to the Hibernate Validator. If the validation fails, Spring immediately aborts the request, throws a MethodArgumentNotValidException, and returns a 400 Bad Request to the client.
2. Common Validation Constraints: @NotNull, @Size, @Email, and more 🚦
Now that the bouncer is at the door, let's give them the rulebook.
Definition: Validation constraints are specific annotations applied to class fields that dictate the acceptable state, format, or size of that field.
Here are the industry-standard annotations you will see and use daily.
The "Not Empty" Trio (A Common Interview Question!)
It is crucial to understand the subtle differences between these three:
@NotNull: The field cannot benull. However, it can be absolutely empty. (e.g.,""is perfectly valid).@NotEmpty: The field cannot benullAND its length/size must be greater than zero. (e.g.,""is invalid, but a string of spaces" "is technically valid).@NotBlank: The field cannot benullAND it must contain at least one non-whitespace character. (e.g.," "is invalid).
Industry standard: Always use @NotBlank for String text fields like names, usernames, and passwords.
Other Essential Constraints
@Size(min =, max =): Enforces length constraints on Strings, Collections, or Arrays.@Email: Ensures the string conforms to a standard email format.@Min/@Max: Validates numeric values (e.g., ensuring an age is logical).@Pattern(regexp = "..."): Uses regular expressions for complex validation (e.g., strict password complexity rules).
Example: The Perfect DTO
import jakarta.validation.constraints.*;
public class UserDto {
@NotBlank(message = "Username cannot be blank")
@Size(min = 3, max = 20, message = "Username must be between 3 and 20 characters")
private String username;
@NotBlank(message = "Email is required")
@Email(message = "Please provide a valid email address")
private String email;
@Min(value = 18, message = "You must be at least 18 years old")
@Max(value = 120, message = "Please provide a valid age")
private int age;
// Getters and Setters omitted for brevity
}Interesting Fact: The message attribute allows you to customize the error response. If you don't provide one, Spring will return a highly robotic, generic message. Custom messages make your API much more friendly for frontend developers to display to end-users!
3. Database Version Control: Why Use Flyway or Liquibase? 🗃️
Definition: Database Version Control (often called Database Migration) is the practice of tracking, managing, and applying changes to your database schema using code, exactly like how you track your application code with Git.
The Problem: Imagine you are working on a team of five developers. You add a phone_number column to your local database to support a new feature, update the Java entity, and push the code to production. However, you forgot to manually log into the production database and run the ALTER TABLE SQL command. The application deploys, attempts to query the phone_number column, and instantly crashes.
Historically, developers passed around text files named schema.sql over Slack or email, whispering "Don't forget to run this before you deploy." This manual process is highly error-prone, untraceable, and terrifying during production deployments.
The Solution: Tools like Flyway or Liquibase automate this entirely. When your Spring Boot application starts up, the migration tool intercepts the boot process, connects to the database, and checks which SQL scripts have already been applied. If there are new scripts, it runs them automatically before allowing the application to fully start.
Real-Life Scenario: Think of database migrations like saving a checkpoint in a video game. If a developer builds a new level (adds a new table) and commits the save file (migration script), anyone who downloads the code will automatically be synced to the exact same game state. No one has to manually build the level themselves.
Flyway vs. Liquibase
- Flyway: Uses plain, raw SQL files. It is heavily favored in the industry for its sheer simplicity. If you know SQL, you already know how to use Flyway.
- Liquibase: Uses XML, YAML, or JSON to abstract database changes. It is powerful if your company requires you to support multiple different database engines simultaneously (e.g., supporting both Oracle and PostgreSQL), but it comes with a steeper learning curve.
Because of its prevalence and simplicity, we will focus on Flyway.
Setup (Spring Boot 3.x)
To integrate Flyway into your application, you need to add its dependencies.
Note: Starting with Spring Boot 3 and Flyway 9+, Flyway separated database-specific drivers into their own packages. If you use MySQL, you must include flyway-mysql alongside flyway-core.
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<!-- Include the module for your specific database engine -->
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-mysql</artifactId>
</dependency>4. Writing Your First Migration Script: Safe Database Evolution 🛠️
Now we need to write the actual scripts that will build our database schema.
The Problem: How does Flyway know which script to run first? And more importantly, how does it know if a script has already been executed so it doesn't accidentally run it twice?
The Solution: Strict file naming conventions and an internal tracking table.
The Naming Convention
Flyway scripts must be placed in a specific folder: src/main/resources/db/migration.
Furthermore, they must follow a very strict naming format: V<Version>__<Description>.sql (Notice the double underscore!).
V1__Create_users_table.sqlV2__Add_phone_number_to_users.sqlV3__Insert_default_admin.sql
Writing the Script
Let's create our very first script. Create a file at src/main/resources/db/migration/V1__Create_users_table.sql:
CREATE TABLE users (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(20) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
age INT NOT NULL
);When you start your Spring Boot application, look closely at your console logs. You will see Flyway booting up, discovering V1__Create_users_table.sql, and successfully executing it against your database.
Under the Hood: The flyway_schema_history Table
How does Flyway avoid running V1 again on the next application restart?
When Flyway runs for the very first time on a fresh database, it silently creates a metadata table called flyway_schema_history. Every time it successfully executes a migration script, it inserts a record into this table containing the version number, description, and a checksum of the file's contents.
On the next startup, Flyway compares the scripts in your src/main/resources folder against the records in flyway_schema_history. Because V1 is already in the table, Flyway safely ignores it.
🚨 The Golden Rule of Database Migrations 🚨
Never, ever, EVER modify a migration script after it has been executed on a shared database.
If you change the contents of V1 after it has already run, Flyway will calculate a new checksum for the file on startup. It will compare this new checksum to the old checksum stored in flyway_schema_history, realize you have tampered with the past, and it will intentionally crash your application to prevent data corruption.
If you made a typo or a structural mistake in V1, you must live with it temporarily and create a brand new script—V2__Fix_V1_mistake.sql—to correct the issue. In the world of database migrations, time only moves forward; we never alter the past!
References & Extra Reading
Challenge
You are tasked with setting up the foundation for a new user registration feature. This involves creating a Data Transfer Object (DTO) in Java to handle incoming registration data with strict validation rules, and writing the initial database migration script using Flyway to create the users table.
Part 1: Java DTO with Validation
Define a public Java class named UserRegistrationDTO. This class must include the following fields with the specified validation constraints from jakarta.validation:
username:- Must not be null or contain only whitespace.
- Must be between 3 and 20 characters long.
email:- Must not be null.
- Must be a structurally valid email address.
password:- Must not be null or an empty string.
- Must be at least 8 characters long.
- Must contain at least one digit, one lowercase letter, one uppercase letter, and one special character (e.g.,
@#$%^&+=).
age:- Must not be null.
- The value must be 18 or greater.
Part 2: Flyway Database Migration
Below your Java class, write the content for a Flyway SQL migration script. The script should be named V1__Create_users_table.sql and must perform the following action:
- Create a table named
users. - The table must have the following columns:
id: A numeric primary key that auto-increments.username: A string column that cannot be null and must be unique.email: A string column that cannot be null and must be unique.password_hash: A string column to store the hashed password, cannot be null.age: An integer column, cannot be null.
Expected result
Your final code should consist of two parts within the editor:
A fully defined
UserRegistrationDTO.javaclass.- It must include imports for all used
jakarta.validation.constraintsannotations. - Each field (
username,email,password,age) must be annotated correctly to enforce all rules specified in the instructions. - For the
password, you are expected to use@Patternwith an appropriate regular expression to meet the complexity requirements. - For other fields, use a combination of annotations like
@NotBlank,@Size,@Email,@NotNull, and@Min.
- It must include imports for all used
A complete SQL
CREATE TABLEstatement for theuserstable.- This statement must be located under the
// File: V1__Create_users_table.sqlcomment. - The SQL syntax must be valid.
- The table schema must match the requirements precisely, including column names (
id,username,email,password_hash,age), data types (e.g.,BIGINT,VARCHAR,INT), primary key, auto-increment,NOT NULL, andUNIQUEconstraints.
- This statement must be located under the