Skip to content

Instantly share code, notes, and snippets.

@dextervip
Forked from anonymous/Entidade.java
Created February 28, 2013 03:00
Show Gist options
  • Save dextervip/5053835 to your computer and use it in GitHub Desktop.
Save dextervip/5053835 to your computer and use it in GitHub Desktop.
public class Car {
/**
* Diz que a variavel não pode ser nula
*/
@NotNull
private String manufacturer;
/**
* Diz que a variavel não pode ser nula e o tamanho tem que ser maior ou igual 2 e no maximo 14
*/
@NotNull
@Size(min = 2, max = 14)
private String licensePlate;
/**
* Diz que a variavel tem que ser maior ou igual 2
*/
@Min(2)
private int seatCount;
public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getLicensePlate() {
return licensePlate;
}
public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
public int getSeatCount() {
return seatCount;
}
public void setSeatCount(int seatCount) {
this.seatCount = seatCount;
}
}
run:
Fev 27, 2013 11:50:33 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 4.3.1.Final
O atributo seatCount deve ser maior ou igual a 2
O atributo manufacturer não pode ser nulo
O atributo licensePlate tamanho deve estar entre 2 e 14
CONSTRUÍDO COM SUCESSO (tempo total: 0 segundos)
public class Teste {
private static Validator validator;
public static void main(String[] args) {
//Chama classe para validar a entidade
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
//Cria entidade com valores fora da validação
Car car = new Car(null, "DD-AB-12AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3", 0);
//Faz a validação e salva as violações de validação
Set<ConstraintViolation<Car>> constraintViolations = validator.validate(car);
if (constraintViolations.size() > 0) {
for (ConstraintViolation<Car> constraintViolation : constraintViolations) {
//System.out.println(constraintViolation);
System.out.println("O atributo "+constraintViolation.getPropertyPath() +" "+ constraintViolation.getMessage());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment