There is a registration form that adds users to the database. Faced the problem that when registering a user with an existing key - it overwrites everything — only the old value, instead of returning an error. As I understand it is necessary to set the login validation, but in the Hibernate library and javax.validation I did not find an annotation that can solve this situation. Tell me, colleagues, is there a library that will help solve my problem, or is it necessary to set your own annotation, which goes to the database and checks if there is a user with this key?

  • the structure of the table, including restrictions, the text of the program, where does it occur? - Sergey

3 answers 3

As I understand it is necessary to set the login validation, but in the Hibernate library and javax.validation I did not find an annotation that can solve this situation.

Naturally, there is no such annotation, because in all applications there are various tables, fields and logic for checking them.

Tell me, colleagues, is there a library that will help solve my problem, or is it necessary to set your own annotation, which goes to the database and checks if there is a user with this key?

Yes that's right.

Here is an example from my project:

  • Thank you, got acquainted with your implementation, but on my project does not want to properly screwed. I will try to enter my implementation. - Dmitriy Smirnov

Yes, you need to check if there is such a login in the database.

select mytable where login=mynewlogin 

If the result returns, then such a login exists, so we change it.

    Faced the problem that when registering a user with an existing key - it overwrites everything — only the old value, instead of returning an error.

    It seems that adding to Hibernate is implemented through currentSession().saveOrUpdate(...); As indicated in the name of the method, Hibernate will add an entity or update if it exists. If so, correct the name of the method to save(...) - Hibernate will return the SQL error of the primary key, and process it.

    • I use spting data. I work with repository models. Save method saveAndFlush (user); - Dmitriy Smirnov