Persistence and validation
What you will learn
Validation rejects malformed requests; persistence stores domain state. These are distinct boundaries, and neither replaces database constraints.
- Apply request validation before domain operations.
- Explain managed entity state and optimistic versions.
- Distinguish validation from persistence constraints.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Jakarta EE examples require the pinned companion Maven project or separately configured illustrative infrastructure. Their predicted results are not execution evidence.
Validate a book request
public class Main { record Input(String title,int copies){Input{if(title==null||title.isBlank()||title.length()>80||copies<0)throw new IllegalArgumentException();title=title.strip();}} public static void main(String[] args) {for(String title:java.util.List.of(" Java "," ")){try{System.out.println(new Input(title,2).title());}catch(IllegalArgumentException e){System.out.println("invalid");}} }}Expected output:
JavainvalidPlain Java constructor validation is independent of Jakarta Validation.
Validate at boundaries
Jakarta Validation 3.1 supports constraints on record components. @NotBlank rejects null, empty and whitespace-only text; @Size limits length but generally treats null as valid. @PositiveOrZero permits zero. @Valid requests cascading validation into an object; it does not by itself reject a null object, so the resource adds @NotNull. A primitive int defaults to zero if a missing JSON field is accepted by the binding implementation; use a boxed Integer plus @NotNull if presence is mandatory. The preview intentionally permits zero copies and does not store data. REST input constraint violations normally map to 400; return-value violations indicate a server defect. Do not expose implementation details in error responses.
Persistence boundary
Jakarta Persistence 3.2 defines entity mapping and entity-manager contracts; a provider implements these. An @Id identifies an entity and @Version supports optimistic concurrency checks. A container-managed persistence context is associated with the appropriate transaction and lifecycle; do not close the injected EntityManager or share a manually created manager across threads. Database constraints remain authoritative for uniqueness and concurrent changes. Jakarta Data 1.0 offers repository abstractions; it is not identical to Spring Data. The lab entity is illustrative only; the running REST sample is read-only except for preview. An actual JTA persistence unit, schema and configured datasource are required to test persistence.
Detect a stale version
public class Main { static class Store{long version; synchronized boolean update(long expected){if(expected!=version)return false;version++;return true;}} public static void main(String[] args) {var store=new Store();long snapshot=store.version;System.out.println(store.update(snapshot));System.out.println(store.update(snapshot)); }}Expected output:
truefalseA synchronized memory model illustrates conflicts; no ORM or database lock is exercised.
Record request constraints
Source-reviewed, NOT RUN. File lab-fixtures/jakarta-ee-v42/src/main/java/example/catalog/BookInput.java; use the companion lab README.
package example.catalog;import jakarta.validation.constraints.*;public record BookInput(@NotBlank @Size(max=80) String title, @PositiveOrZero int copies) {}Predicted behavior: Blank titles and negative copy counts fail validation when the container validates the input.
The preview resource invokes cascading validation; missing primitive values may become zero.
Portable entity mapping
Source-reviewed, NOT RUN. File lab-fixtures/jakarta-ee-v42/illustrative/BookEntity.java; use the companion lab README.
package example.persistence;import jakarta.persistence.*;@Entity @Table(name="books")public class BookEntity { @Id private String id; @Version private long version; @Column(nullable=false,length=80) private String title; protected BookEntity() {} public BookEntity(String id,String title){this.id=id;this.title=title;} public String getTitle(){return title;}}Predicted behavior: A configured provider maps identity and version fields.
Illustrative source outside WAR; no database or persistence unit supplied.
Common mistakes
Do not assume @Valid checks null, that @Column alone creates or enforces a deployed schema, or that a plain-Java version model proves database locking.
Practice
Implement a record validating nonblank title, maximum length 80, and nonnegative count. Print accepted for a zero count and rejected for blank title and negative count.
Expected output:
acceptedrejectedrejectedCompare with the manual review criteria.
Official reading: Persistence · Inventory · REST. Jakarta EE execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Persistence and validation — knowledge check
Jakarta EE enterprise Java reasoning.
What does @Valid alone guarantee for a null value?
What annotation marks optimistic version state?
What protects unique keys against concurrent writes?
Who manages an injected EntityManager lifecycle?
What is the status of the memory model?