How to validate a JavaEE6 Bean in a job

Normally bean validation is already integrated in frameworks like PrimeFaces, but what if we're working on data in a batch job? In these cases we won't have access to these libraries. So how do we validate our bean? Here's how I did it.

For example we have an entity bean Customer:
@Table(name = "CUSTOMER")
public class Customer implements Serializable {

 @GeneratedValue(strategy = GenerationType.SEQUENCE)
 private Long id;
 @Size(min = 1, max = 50)
 @Column(name = "FIRST_NAME")
 private String firstName;
 @Size(min = 1, max = 50)
 @Column(name = "LAST_NAME")
 private String lastName;

To validate we need to inject the bean Validate and validate our bean, here's how:
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;

public class CustomerImport {

 private Validator validator;
 private void validate(Customer customer) {
  Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
  if (!violations.isEmpty()) {
   throw new ConstraintViolationException(
     new HashSet<ConstraintViolation<?>>(violations));
How to validate a JavaEE6 Bean in a job How to validate a JavaEE6 Bean in a job Reviewed by Edward Legaspi on Thursday, October 24, 2013 Rating: 5

No comments:

Powered by Blogger.