views:

124

answers:

3

I'm using Hibernate JPA and Spring in my project. Suppose if I try to insert a record with duplicate key value, the insert query will throw an exception.

Now, is it possible to get the table name, field name and possible cause for the exception from the SQL Exception object at run time !?

+1  A: 

SQLExceptions tend to just wrap up database errors, you can only get that sort of information if it was included in the error that your database threw. In my experience of debugging hibernate and JDBC stuff, I would hazard that the answer to this question is generally "no", but there might be exceptions.

Kurley
A: 

hibernate wraps SQLException as JDBCException and tries to convert it to more meaning full exception like ConstraintViolationException using SQLExceptionConverter which is attached to SessionFactory.

SQLException sqlException = ((JDBCException)ex).getSQLException();
prateek urmaliya
+1  A: 

As the other answers have mentioned, most of the time you are limited to what you are given by the database. However in some cases Hibernate can tell you the problem - it won't be the table and field, but can be the entity and 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());
    }
}
Damo