Hibernate may throw a ConstraintViolationException when trying to insert a row that violates a constraint (including a unique constraint). If you do not get this exception, you can get another general Hibernate exception - it depends on the version of Hibernate and the ability of Hibernate to match the MySQL exception with the Hibernate exception in the version and type of database you are using (I have not tested it for everything).
You will only get an exception after calling flush (), so you need to make sure that this is also in your try-catch block.
I would be careful in implementing solutions in which you verify that the string exists in the first place. If several sessions update the table at the same time, you can get a race condition. Two processes read the line almost at the same time to see if it exists; they both discover that they are not, and then they both try to create a new line. Someone will win depending on who wins the race.
The best solution is to try to insert the first one, and if she fails, suppose she was already there. However, as soon as you get an exception, you will have to roll back to limit the use of this approach.
source share