Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to @Validate unique username in spring?

Let's assume that I have a form where I might submit username(@NaturalId) and password for a new user.

I would like to add the user with a unique username. How can I use @Valid annotations to validate this constraint? And if username is not unique how can I display this information in jsp via <form:error/>?

like image 818
user902691 Avatar asked Jun 13 '13 16:06

user902691


People also ask

How do I create a unique spring boot userName?

Set unique = true on your property in your entity class. @Column(unique = true) private String userName; But this will not work with @valid, instead throw an exception on persistence. You have to use an appropriate logic to handle that.

What is Hibernate Validator?

Hibernate Validator allows to express and validate application constraints. The default metadata source are annotations, with the ability to override and extend through the use of XML. It is not tied to a specific application tier or programming model and is available for both server and client application programming.


2 Answers

AFAIK there isn't an annotation to do this. You have two options

One, create a custom validator annotation. Here is a very good example. Make a call to your DAO class and check the availability in the validator implementation

    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {

    return userDAO.userNameAvailable(object); //some method to check username availability
    }

OR

Set unique = true on your property in your entity class.

    @Column(unique = true)
    private String userName;

But this will not work with @valid, instead throw an exception on persistence. You have to use an appropriate logic to handle that.

The first solution isn't fool proof. Check this answer on SO.

The second will will never fail.

UPDATE

As NimChimpsky commented, using both together will be a concrete solution.

like image 75
shazinltc Avatar answered Sep 25 '22 17:09

shazinltc


JSR-303 does not support what you want (something like a @Unique constraint). You have to write you own validator. How can this be done is explained here: https://community.jboss.org/wiki/AccessingtheHibernateSessionwithinaConstraintValidator

But before doing that make sure you read this answer: https://stackoverflow.com/a/3499111/1981720

And this sentence from the previous article:

The reason @Unique is not part of the built-in constraints is the fact that accessing the Session/EntityManager during a valiation is opening yourself up for potenital phantom reads.

like image 42
lunr Avatar answered Sep 21 '22 17:09

lunr