What is the best way to deal with potential duplicate fields being inserted into a table where that is not allowed? For example:
CREATE TABLE Person (Id INT, Name VARCHAR(255), Email VARCHAR(255), UNIQUE (Email));
Then we try to save 2 different Person objects with the same email:
session.save(new Person("John", "a@b.com"));
session.save(new Person("Adam", "a@b.com"));
I will, of course, get an exception. It's pretty ugly and the messages are vague:
Code:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.UncategorizedSQLException: Hibernate flushing: Could not execute JDBC batch update; uncategorized SQLException for SQL [insert into Person (Id, Name, Email) values (?, ?, ?)]; SQL state [null]; error code [0]; failed batch; nested exception is java.sql.BatchUpdateException: failed batch
With the following root cause:
Code:
java.sql.BatchUpdateException: failed batch
My question is what is the best way to handle this? Obviously one option is to check the database before performing a session.save(person). In my particular application and in this particular situation I think I can get away with that, but in general that's a little ugly as an exception can still happen if both checks happen near the same time. Instead I would think catching the appropriate exception would be a more elegant solution. But which exception do I catch for this? How do I know duplicate unique fields was the error?