Java
Course: Developing Persistence
Tier of an Enterprise
Application using JPA
Session: Bean Validation with
JPA
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
By the end of this session, you will be able to understand:
• Overview of JSR-303 Bean Validation 1.0
• JSR-317 JPA 2.0 support for Bean Validation
• OpenJPA modifications for Bean Validation
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Overview of JSR-303 Bean Validation
Bean Validation Spec.
Constraint Definitions.
Constraint Descriptors.
Spec Required Constraints.
Validation Groups.
Spec Defined Exceptions.
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Bean Validation Spec
JSR-303 – JCP lead is Red Hat
Hibernate Validation 4.0 will be the RI
• The PFD/1.0 CR1 was the last publicized version from JCP
website.
• Current validation-api source is hosted in a public repo, so spec
updates since the PFD can be tracked.
Agimatec-Validation by agimatec GmbH on Google Code is the
only other implementation we've found.
• Has not finished implementing all of the PFD items.
• Does not use the TraversableResolver.
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Constraint Definitions
A null element is considered to be valid.
Each constraint supports a List<T>
Implementations must provide a MessageResourceBundle with
some common predefined constraint messages.
Constraints can be declared on interfaces and are cumulative
• Traversable fields, traversable methods (getters only), classes
(interfaces and superclasses) and traversable associations
• Uses [Link]() to determine if a given
property should be accessed.
Constraints are not processed in any particular order.
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Constraint Descriptors
Constraints can be provided by annotation or XML
• No Spec requirement for Java SE 6
• META-INF/[Link]
• XML overrides annotations unless ignore-annotations is set to
false on the class descriptors
• Descriptors can only be provided for a given class once
Invalid arguments lead to a IllegalArgumentException,
ConstraintDeclarationException or ValidationException.
A property can have constraints on both fields and methods.
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Spec Required Constraints
@AssertTrue/AssertFalse(Boolean value) – Boolean.
@DecimalMax/DecimalMin(String value) – BigDecimal,
BigInteger, String, byte/Byte, short/Short, int/Integer, long/Long.
@Digits(int integer, int fraction) - BigDecimal, BigInteger, String,
byte/Byte, short/Short, int/Integer, long/Long
@Future/Past() – Date, Calendar
@Max/Min(long value) – BigDecimal, BigInteger, String,
byte/Byte, short/Short, int/Integer, long/Long
@Null/NotNull() – Object
@Pattern(String regexp, Flag flags) - String
@Size(int min, int max) – String, Collection, Map, [Link]
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Validation Groups
Default group includes all constraints.
Uses interfaces to define subsets of constraints.
Can inherit from other groups.
GroupSequence can be used to redefine the Default group for a
class.
GroupSequence controls the order groups are processed and is
the only way to define constraint ordering (one constraint per
group).
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Validation Groups
Runtime exceptions
• ConstraintViolationException – generated by the framework
(JPA2) if validation failures occur and contains the set of
specific ConstraintViolation(s)
• ConstraintViolation – contains the failure details: constraint
descriptor, message, class, property and value
Compile time exceptions (annotation processor)
• ConstraintDefinitionException – illegal constraint
• ConstraintDeclarationException – invalid constraint argument
• UnexpectedTypeException – invalid property type
• GroupDefinitionException – cyclic graph, illegal override
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
JSR-317 JPA 2.0 support for Bean Validation
Validation Overview.
Integration Diagram.
Validator Factory.
Validation Modes.
Validation Groups.
Validation Exceptions.
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Validation Overview
Validation is optional. The JPA 2.0 Spec does not require a Bean
Validation implementation.
A TraversableResolver must be supplied by the persistence
provider, so validation:
• Does not cause unloaded attributes to be loaded (confirm to
[Link]/Eager)
• Validation cascading or embedded attributes (either marked
with @Valid) does not traverse entity associations
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Integration Diagram
[Link] d or
Provide
Default
EntityManagerFacto
[Link]
Validation Configuration
ry Create ValidatorFacto
Attach
(mode and
to
validation groups) Create isTraverseablery Create
[Link]
(entity)
TraversableResolver [Link]
isLoaded(entit Validato
[Link] y) idate r
)
EntityManager Vaelntity
PrePersist (
Implicit or
Explicit
PreUpdate Validation Employee
Events (entity)
Manage @NotNull
PreRemove d String
name
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Validator Factory
Java EE containers and Java SE applications can provide a
[Link] in the EMF properties Map.
A default instance is obtained from the Validation implementation
in the classloader (if one is present) if none are supplied.
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Validation Modes
[Link]
• Auto (default) – if a validation provider is available, then
validation should occur
• Callback – validation is required and a PersistenceException
must be thrown if a provider cannot be obtained
• None – no validation should be attempted and the lack of a
validation provider should not cause an exception
Can be set per PU
• <validation-mode> element in the [Link]
• [Link] in the EMF properties Map
EMF supplied properties will override the XML.
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Validation Groups
Defines validation groups for entity life-cycle events
• [Link]-persist – Default
validation group called after all other PrePersist callbacks.
• [Link]-update – Default
validation group called after all other PreUpdate callbacks.
• [Link]-remove – Default
validation group is NOT called after all other PreRemove
callbacks.
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Validation Exceptions
[Link] – thrown if validation
mode is Callback and a provider could not be obtained
[Link] – thrown if any
constraint failures occur and contains the set of
[Link] instance(s)
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
OpenJPA modifications for Bean Validation
Configuration Updates.
Integration Diagram.
LifecycleEventManager.
TraversableResolver.
Unit Testing.
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Configuration Updates
New configuration properties
• [Link] – EMF property
• [Link] – PU or EMF property
• [Link]-persist – PU or EMF
property and entity annotation
Pluggable Validator
Removes dependency on JSR-303 APIs
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Configuration Updates
Pluggable LifecycleEventManager
• Loaded during EMF creation in PersistenceProviderImpl by
loadValidator() just like loadAgent(), as old invocation location
in BrokerImpl was restricted to kernel classes
• Requires access to openjpa-persistence classes after all config
derivations are loaded
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
Integration Diagram
OpenJPAConfiguration
TraversableResolve
Validation r
ValidationMode
Configuration
Validator Impl (JSR-303 based)
Properties via
[Link] or Validation
Map on Factory
createEMF() Lifecycle Validation
Groups (Validating)
LifecycleEventManager
Validator
Broker Validating (JSR-303
LifecycleEventManage based)
(Validating) r Validation
Validat Groups
LifecycleEventMana
or Validation
ger
Factory
ValidatingLifecycle
Validator
EventManager created if:
- ValidationMode != NONE
- Validation API and factory
available
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
LifecycleEventManager
Extended to provide event based Validation
• ValidatingLifecycleEventManager
Validation mode and provider availability determine whether to
use standard or validating event manager
• Reflection used to determine existence of JSR-303 provider and
API (through ValidationUtils)
• Eliminates runtime dependency on API and provider
Calls Validator upon lifecycle events
Interacts with validation provider agnostic interface
• Allows plugging in any validation implementation which
implements OpenJPA's validation interface
TALENTSPRINT | © Copyright 2015
Bean Validation with JPA
TraversableResolver
Provided to ValidationFactory upon Validator creation Simple
interface with single isTraversable method
Primary role is to prevent loading of unloaded entities/ attributes
and traversal to related entities
Spec dictates the need for a provider specific resolver to meet
loading and relationship traversal reqs.
• OpenJPA will provide and register a TraversableResolver upon
Validator creation
Container vs. provider level requirements unclear.
TALENTSPRINT | © Copyright 2015