A constraint is a rule that restricts valid object or database states. Constraints protect data integrity across the user interface, business and persistence layers, and SQL storage, with the database serving as the final validator. section 3.3.2
Common validation constraints express rules that would otherwise require repeated conditional checks:
- Require a value with @NotNull. section 3.3.2
- Restrict text length with @Size, such as two through 255 characters for an item name. section 3.3.2
- Require a number or date to remain within an allowed range, including a future auction-end date with @Future. section 3.3.2
- Require text to match a regular expression when a specific format is necessary. section 3.3.2
Listing 3.6 Applying validation constraints on Item entity fields
Path: Ch03/validation/src/main/java/com/manning/javapersistence/ch03 /validation/Item.java import javax.validation.constraints.Future; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.Date; public class Item { @NotNull @Size( min = 2, max = 255, message = "Name is required, maximum 255 characters." ) private String name; @Future private Date auctionEnd; }
Annotating entity fields keeps validation rules beside the domain model and makes them available as ORM-related metadata. section 3.3.2
Testing a constrained object
Create a Validator from Validation.buildDefaultValidatorFactory(), validate an Item instance, and inspect ConstraintViolation results. An Item whose auctionEnd is the current date produces one violation for the auctionEnd property.
Constraint placement affects tradeoffs. A single-table inheritance schema keeps queries and evolution simple but may require nullable columns, weakening data integrity. Table-per-subclass joins normalize the schema and simplify integrity-constraint definition, at the cost of more complex implementation and potentially slower complex-hierarchy queries. section 7.9


















