0% found this document useful (0 votes)
4 views

12.java - Course 3 - S13 - Bean Validation

Uploaded by

Vikas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

12.java - Course 3 - S13 - Bean Validation

Uploaded by

Vikas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

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 TraversableResolver.isTraversable() 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/validation.xml
• 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, Array.length

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
FetchType.Lazy/Eager)
• Validation cascading or embedded attributes (either marked
with @Valid) does not traverse entity associations

TALENTSPRINT | © Copyright 2015


Bean Validation with JPA

Integration Diagram

javax.persistence d or
Provide
Default
EntityManagerFacto
javax.validation
Validation Configuration
ry Create ValidatorFacto
Attach
(mode and
to
validation groups) Create isTraverseablery Create
javax.validation
(entity)
TraversableResolver javax.validation

isLoaded(entit Validato
javax.persistence 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
javax.persistence.validation.factory 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
javax.persistence.ValidationMode
• 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 persistence.xml
• javax.persistence.validation.mode 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
• javax.persistence.validation.group.pre-persist – Default
validation group called after all other PrePersist callbacks.
• javax.persistence.validation.group.pre-update – Default
validation group called after all other PreUpdate callbacks.
• javax.persistence.validation.group.pre-remove – Default
validation group is NOT called after all other PreRemove
callbacks.

TALENTSPRINT | © Copyright 2015


Bean Validation with JPA

Validation Exceptions
javax.persistence.PersistenceException – thrown if validation
mode is Callback and a provider could not be obtained

javax.validation.ConstraintViolationException – thrown if any


constraint failures occur and contains the set of
javax.validation.ConstraintViolation 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
• javax.persistence.validation.factory – EMF property
• javax.persistence.validation.mode – PU or EMF property
• javax.persistence.validation.group.pre-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
persistence.xml 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

You might also like