no

Introduction to bean validation in JavaEE

Normally bean validation is already integrated in frameworks like PrimeFaces, but what if we're working on data in a batch job? In these...

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));
  }
 } 
 
}

Related

javaee 1635962898363137516

Post a Comment Default Comments

item