Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

jakarta ee - Using Java EE 6 Bean Validation

I am trying to use Java EE 6 Validation as specified here

http://docs.oracle.com/javaee/6/tutorial/doc/gircz.html

I have annotated a simple field

@Max(11)
@Min(3)
private int numAllowed;

The docs says "For a built-in constraint, a default implementation is available" but how do I specify this. My constraints checks are not kicking in. I would expect it to work on calling of the setter method for the field. The only import in my class is

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

How/where do I specify the implementation? I am putting the constraint on a filed in a simple POJO not an @Entity class, is this ok?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your use of the annotations is just fine. There's a validator implementation for each of those rest assured.

However, at some point you need to trigger the validation of this POJO. If it were an @Entity it would be your JPA provider which triggers validation, in your case you need to do it yourself.

There's a nice documentation for Hibernate Validator which is the reference implementation for JSR-303.

Example

public class Car {
    @NotNull
    @Valid
    private List<Person> passengers = new ArrayList<Person>();
}

Using Car and validating:

Car car = new Car( null, true );

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );

assertEquals( 1, constraintViolations.size() );
assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() );

You may also want to read how bean validation is integrated with other frameworks (JPA, CDI, etc.).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...