Custom hibernate validator that retrieves information from database in seam
6 comments Posted by Rey Jexter Bumalay at 4:37 AMUsing hibernate validation, we can decouple the validation rules and at the same time make it reusable for future projects. For example we want to validated if the username given already exist on the database and usually we just put our validation logics on the session bean or action (in struts). At the start of the project this looks ok but as the project progress and some new specification changes, new functionalities are added and some parts of your code gets refactored things get a bit messier.
Instead of simply dumping all the validation logic on the session bean we can create a custom hibernate validator which later can be used by annotating the getter of the entity property. Below is my code to validate if the username if it already exist on my database.
Username.java - The validator annotation definition
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ValidatorClass(UsernameValidator.class)
public @interface Username {
String message() default "Username already exists";
}
UserValidator.java - The validator class implementation
public class UsernameValidator implements ValidatorUser.java - and finally, the entity class, Serializable{
private static final long serialVersionUID = -1458203631809206211L;
public void initialize(Username parameters) {
}
public boolean isValid(Object value) {
UserHome userHome = (UserHome) Component.getInstance("userHome");
User user = userHome.findUser((String)value);
// return true if no user with the given value was found
if(user == null) {
return true;
}
// return true if the user retrieved is equals to the current instance in home
if(user.getId() == userHome.getInstance().getId()) {
return true;
}
// return false if the username exist on our database
return false;
}
}
public class User extends BaseEntity {The validation code above simply tries to retrieve the user from database. If it returned null it means that no user with the given user name exist to it returns true (meaning the validation is successful). If a user with the given username is found, it checks if the user instance from userHome component is the same so that the validation will still be successful if we try to save it without modifying anything. Returning false will cause the validation process to return error message which can be later display by using
private static final long serialVersionUID = 6148649482941380604L;
private String username;
@Length(min=3, max=32, message="Username should be 3-32 characters")
@NotNull
@Username
public String getUsername() {
return username;
}
}
References:
hibernate docs
hibernate validator source codes
Labels: hibernate, seam, validation