Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

Unique Combination Validation With Error Message In Hibernate

hibernate spring validation

  • Please log in to reply
No replies to this topic

#1 dlinx90


    CC Regular

  • Member
  • PipPipPip
  • 34 posts

Posted 22 May 2012 - 01:16 AM

0 down vote favorite share [fb] share [tw]

Hi everyone,

I am developing a web application using Hibernate and Spring.

What I am wondering is how I can validate a unique combination of columns and show an error message to the user?

Currently I am using a custom validator to validate a unique field. I am wondering if it is possible to expand the validator to be able to handle combinations of columns that should be unique. The reason I am using a custom validator is because I want to display error messages to the user.

Here is the custom validator:

@Constraint(validatedBy = UniqueIdValidator.class)
public @interface Unique {
    String message() default "already exits";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

     * The mapped hibernate/jpa entity class
    Class<?> entity();

     * The property of the entity we want to validate for uniqueness. Default name is "id"
    String property() default "id";   

public class UniqueIdValidator implements ConstraintValidator<Unique, Serializable> {

    private SessionFactory sessionFactory;

    private Class<?> entityClass;
    private String uniqueField;

    public void initialize(Unique unique) {
        entityClass = unique.entity();
        uniqueField = unique.property();

    public boolean isValid(Serializable property, ConstraintValidatorContext cvContext) {
        Criteria crit = sessionFactory.getCurrentSession().createCriteria(entityClass);
        crit.add(Restrictions.eq(uniqueField, property));
        return crit.list().isEmpty();


Is using a custom validator the easiest way to achieve my goal of both validation and error messages? I know i could use something like
uniqueConstraints = {@UniqueConstraint(columnNames={"column1", "column2"})}

to get the unique combination constraint but in that case is there any easy way to display an error message instead of just throwing an exception?
Thank you for your time and help.
  • 0

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download