Getting the name of the field and table that threw the exception from the SQL Exception object
I am using Hibernate JPA and Spring in my project. Suppose if I try to insert a record with a duplicate key value, the insert request throws an exception.
Now, is it possible to get the table name, field name and possible reason for the exception from the SQL Exception object at runtime ??
a source to share
As mentioned in other answers, most of the time you are limited to what you give to the database. However, in some cases Hibernate can tell you about the problem - it will not be a table and a field, but it can be an entity and a property
For example, if you try to put too large a value in a column, you can use this:
try {
entityManager.persist(object);
} catch (InvalidStateException e) {
log.info("Caught Hibernate exception: #0", e.getClass().getName());
InvalidValue[] invalidValues = e.getInvalidValues();
for(InvalidValue invalidValue : invalidValues) {
log.info("Invalid Property #0 has value: #1", invalidValue.getPropertyName(), invalidValue.getPropertyName());
}
}
a source to share
SQLExceptions tend to just terminate database errors, you can only get this kind of information if it was included in the error your database threw. In my experience of debugging hibernation and JDBC stuff, I would venture that the answer to this question is no at all, but there may be exceptions.
a source to share
hibernate wraps the SQLException as a JDBCException and tries to convert it to a larger value, meaning a full exception like ConstraintViolationException, using a SQLExceptionConverter that is attached to the SessionFactory.
SQLException sqlException = ((JDBCException)ex).getSQLException();
a source to share