Thursday, 4 July 2013

Get all error message of hibernate annotation in Map (Field,Error Message)


import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "user")
public class User1 extends AbstractDocument {

public User1() {

}

public User1(String displayName, String username, String password) {
this.displayName = displayName;
this.username = username;
this.password = password;
}

@NotNull
@NotBlank
@NotEmpty
@Length(min = 6, max = 8)
private String displayName;

@NotNull
@NotBlank
@NotEmpty
@Length(min = 6, max = 8)
private String username;

@NotNull
@NotBlank
@NotEmpty
@Email
@Length(min = 6, max = 8)
private String password;

public String getDisplayName() {
return displayName;
}

public void setDisplayName(String displayName) {
this.displayName = displayName;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

@Override
public String toString() {
return "User [displayName=" + displayName + ", username=" + username
+ ", password=" + password + ", toString()=" + super.toString()
+ "]";
}

public static void main(String[] args) {

User1 user = new User1("", "", "qqq");

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();

Set<ConstraintViolation<User1>> constraintViolations = validator
.validate(user);

System.out.println("size:" + constraintViolations.size());

Map<String, String> map = new HashMap<String, String>();

for (ConstraintViolation<User1> obj : constraintViolations) {

String key = obj.getPropertyPath().toString();

if (!map.containsKey(key)) {
map.put(key, obj.getMessage());
} else {
map.put(key, map.get(key) + "," + obj.getMessage());
}
}
System.out.println(map);

}

}

OUTPUT:

size:6
{password=not a well-formed email address,length must be between 6 and 8, username=may not be empty,length must be between 6 and 8, displayName=length must be between 6 and 8,may not be empty}


No comments: