Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine a database constraint violation in java?

I am relying on the database to tell me if there is a uniqueness violation so I would like to know when the exception I am getting is some sort of constraint violation. It looks like this is exactly what I need: java.sql.SQLNonTransientException

But it is new to 1.6 and I'm not confident my database drivers are new enough. I use many DBMSs and have many clients, so relying on the driver to be up-to-date is difficult.

Is there a generic way to check for this pre-java 1.6 other than searching the exception message for "constraint"?

like image 498
rjcarr Avatar asked Dec 17 '22 04:12

rjcarr


1 Answers

No, there is no general mechanism for this. It's dependent on the database and the JDBC driver you use.

SQLException has getErrorCode and getSQLState methods that return information that you can use to determine the fine meaning of a given exception, but you'll have to make it specific to driver+database.

Spring uses those same indications and a database-specific lookup table to translate SQLException into its own database-agnostic hierarchy of exceptions. You may be able to use that, or at least look at its sour e code to see how it works.

like image 64
skaffman Avatar answered Dec 25 '22 22:12

skaffman