问题
Given I have an exception of type 'java.sql.SQLIntegrityConstraintViolationException'
Is it possible to programmatically determine the column (or columns) in error? I ask this because I would like to map the error back to the client's data model to indicate field in error (for example a violation of a unique key).
For example given a duplicate value is attempted to be inserted on a table, the 'java.sql.SQLIntegrityConstraintViolationException' exception would be thrown with the following message:
The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'INDEX_NAME' defined on 'COLUMN_NAME'.
Having the error type, and fields in error would allow the client to nicely indicate which input was in error, and the error message. I guess I could try passing the error message, to get the info that I need (obviously that would not be a nice solution.)
Does anyone know of a good way to extract the column in error from the exception?
回答1:
Quite a bit of this is going to be vendor specific. You can learn a lot from the sql error code. But as the javadoc noted, the value is vendor specific. Spring has a utility which is able to translate these codes (with support for many vendors) into a more specific exception hierarchy. In the case of a constraint violation you would likely get a DataIntegrityViolationException, but that still would not provide explicit access to the index name being violated. The message, however, likely would include the index name.
来源:https://stackoverflow.com/questions/22600993/given-a-java-sql-sqlintegrityconstraintviolationexception-is-it-possible-to-de