Looking for a JavaEE Architect or Potential Tech Co-Founder?
Please don't hesitate to contact me.

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:
@Entity
@Table(name = "CUSTOMER")
public class Customer implements Serializable {

 @Id
 @GeneratedValue(strategy = GenerationType.SEQUENCE)
 private Long id;
  
 @NotNull
 @Size(min = 1, max = 50)
 @Column(name = "FIRST_NAME")
 private String firstName;
 
 @NotNull
 @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;

@Stateless
public class CustomerImport {

 @Inject
 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.