Hi all,
I have a problem with Hibernate Exception. I created a user object and saving the user object. In the user object I have a username which is unique. When I am inserting into MySQL using hibernate with duplicate username in the database I catch the HibernateException and display the Message but I get an empty Message of this Exception, for example in this code
Code:
try{
Long userId = (Long)session1.save(user);
logger.debug("The UserId after Insert ", userId);
tx1.commit();
} catch (HibernateException hEx) {
logger.error("The Error - : ", hEx.getMessage() );
tx1.rollback();
} finally {
session1.close();
}
The log file is as shown below with an empty Message but the JDBCExceptioReporter shows the
Error Message which I need for displaying to the front end user.
Code:
[java] 12:50:45,718 WARN JDBCExceptionReporter:100 - SQL Error: 1062, SQL
tate: 23000
[java] 12:50:45,718 ERROR JDBCExceptionReporter:101 - Duplicate entry 'cad
567' for key 'US_USERNAME'
[java] 12:50:45,788 ERROR HibernateUserTest:? - The Error - :
[java] 12:50:45,848 INFO SessionFactoryImpl:805 - closing
[java] 12:50:45,848 INFO DriverManagerConnectionProvider:170 - cleaning u
connection pool: jdbc:mysql://localhost/test
I have tried to use the ConstraintViolationException of Hibernate and also of MySQL and still the message is empty. I tried catching JDBCException and further getting the SQLException
Code:
catch (JDBCException hEx) {
logger.error("The Error - : ",(MySQLIntegrityConstraintViolationException)hEx.getSQLException());
}
I get the following logger error with the complete stack trace
Code:
[java] 13:21:12,345 WARN JDBCExceptionReporter:100 - SQL Error: 1062, SQLS
tate: 23000
[java] 13:21:12,345 ERROR JDBCExceptionReporter:101 - Duplicate entry 'cad4
567' for key 'US_USERNAME'
[java] 13:21:12,345 ERROR HibernateUserTest:? - The Error - :
[java] com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException
: Duplicate entry 'cad4567' for key 'US_USERNAME'
[java] at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:931)
but if I try getMessage() its empty -
Code:
logger.error("The Error - : ",
((MySQLIntegrityConstraintViolationException)hEx.getSQLException()).getMessage() );
In this particular example there is one unique key but say if I have 2 unique keys and either or both values entered by the user is duplicate and I need to inform the front end which of the values entered by the user is duplicate and for which I need to catch the correct message and show back to the front end user just as reported by the JDBCExceptionReporter - Duplicate entry 'cad4567' for key 'US_USERNAME'. Is this possible ? or am I doing something wrong with the exception handling? I would appreciate if the forums experts would clear my doubts.