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));
}
}
}
0 nhận xét:
Đăng nhận xét