Reputation: 585
i'm working on a java web app. The App is a REST style backend. I'm using spring mvc as my web framework and JPA/Hibernate for the persistance. The database is mysql.
I have a table in the database, where i store a simple text value with an id. So i have two columns there. However i want to make those text values unique. Already set this in sql.
Now I'm writing a unittest to handle what happens when somebody tries to insert the same string multiple times. Spring returns me a DataIntegrityViolationException. The root cause is a MySQLIntegrityConstraintViolationException. From the root cause i can get the sqlErrorCode.
But is there a better way to handle this? Because i don't want to have the dependecy to the mysqlexception and there error code in my code.
Upvotes: 2
Views: 2311
Reputation: 27383
I find it inconvenient to search the DB exceptions wrapped by spring data for their root cause. I would manually check for uniqueness before persisting the new entry to the database.
Remember, the exception thrown by spring is a RuntimeException
, and you should not handle RuntimeException
s as these indicate a "bug" in the code. It's your responsibility that this excpetion is never thrown in the first place.
Upvotes: 1