Sunday, August 6, 2017

javax.validation.ConstraintViolationException: validation failed for classes

If you are working on Hibernate and face this kind of exception, then don’t be surprised. The exception is self-explanatory. It says there is a constraint violation for validation. If you check the stack trace it can show you the class and the line of the code where the exception had been occurred.  The most probable cause might be validation rule applied in the model class. I am giving an example here which mostly happen during the development. Let me say I have an user_account table having Id. username, Password, email, account_status.  All the fields are of String data type except the account_status which is of small Integer type and Id is auto incremented Integer number. Suppose I have created a model for the user_account table like the one below.

@Entity(name="user_account")
public class userAccount {

                @Id
                @GeneratedValue(strategy = GenerationType.AUTO)
                private Integer id;

                @NotBlank(message = "Please enter your username.")
                private String username;
                @Size(min = 8, max = 15, message = "Your username must between 8 and 15 characters")

                @NotEmpty(message = "Please enter your password.")
                @Size(min = 8, max = 15, message = "Your password must between 6 and 15 characters")
                private String password;

                @NotEmpty(message = "Please enter your email.")
                private String email;
                @Size(min=1, max=2)
                private Integer account_status
                // getter setter methods to be called below this line
}

So in the above model class though seems to be ok, you can get exception if you make simple mistakes. For example, you have set the password max limit to 15 and you a 15 character or less value as your password. It seems perfect till now. But if you are hashing your password for security purpose the length might exceed 15. Once the length of the password exceeds 15, your model will throw the above exception as the validation set to 15. So you have to increase the length of the password in the model

Second one is, if you have checked the model I have set the size of an account_status. Size validation does not work for Integer type field. So we can have our second exception at that above point.

If you are using hibernate validation, make sure to read the hibernate validation document and follow accordingly otherwise the above exceptions will keep bothering and can take considerable development time to debug and resolve the issue.

No comments:

Post a Comment