Get startedGet started for free

Constraint enforcement

1. Constraint enforcement

Let's learn how to ensure data quality using annotations.

2. Quality control for data

Validation annotations are like quality control checkpoints. Let's see them in action for a chocolate factory. When tracking international chocolate sales, errors creep in - missing countries, invalid amounts, or negative boxes shipped can slip into our data. Without validation, an incorrect entry of 1000 boxes instead of 100 boxes can trigger expensive shipping mistakes, while missing country codes might cause tax compliance headaches.

3. Basic validation annotations

Let's import annotations from the `jakarta.validation.constraints` package. In our `ChocolateSale` class, we place annotations directly above each field they protect. Annotations start with `@` and tell Java how to handle our data. The `@NotNull` annotation prevents empty values, and we can add a custom error message. We can stack multiple annotations, as shown with the country field where `@NotNull` and `@Size(min = 2, max = 50)` work together - the first prevents empty values, while the second ensures the country name length is reasonable. The product field uses `@NotNull` because shipping empty orders makes no sense.

4. Numeric constraints

Numeric fields also need guardrails: `@Min(0)` prevents negative sales amounts, while `boxesShipped` uses `@Min(1)` and `@Max(1000)` to keep orders within shipping limits.

5. Imports for constraint enforcement

Now that we've defined our constraints, let's enforce them. First we import various classes for validation.

6. Implementing the validator

Next let's break down how validation works. First, we create a `ValidatorFactory`, which gives us the tools to check our data. From this factory, we get a `Validator` that will look for problems in our sales data. When we call `validateSale` with a `ChocolateSale` record, the `validator` checks if everything follows our rules (like valid dates and amounts), and returns a list of any problems it finds. If no problems are found, the list is empty.

7. Handling validation results

Let's see what happens when bad data hits our validation rules. James enters an impossible sale: no country, a negative amount, and too many boxes shipped. Our validator returns a list of `violations` that we print with `getMessage`. If `violations` exist, we throw a `ConstraintViolationException` to stop the program and avoid processing an invalid sale.

8. Validation output

Clear error messages like "Country cannot be empty" and "Sales amount must be positive" help staff spot mistakes immediately. When violations occur, the `ConstraintViolationException` halts the program, preventing bad data from causing distribution problems.

9. Validation prevents costly errors

We explored how validation annotations like @NotNull, @Size, @Min, and @Max catch data errors early with our chocolate factory example. These techniques apply universally - from financial transactions to inventory management - ensuring systems operate on reliable data. Validation serves as a first line of defense, preventing costly errors across industries where accuracy matters.

10. Let's practice!

Over to you!

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.