Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA/Hibernate exception handling

I'm using JPA/Hibernate (a newbie at them). When an exception occur (could be an unique constraint violation) I want to catch it and show some application meaning messages, instead of printing the stack trace.

Does Hibernate provide some tool to get info (maybe database independent) about exceptions?

like image 886
Francesco Avatar asked Jan 03 '12 17:01

Francesco


People also ask

How to handle exceptions in hibernate?

When Hibernate interacts with the database it throws SQLException. Hibernate provides better handle than the JDBCException. Developers can use the try and catch block to handle the exceptions. Put the line of code that may cause an exception in a try block and according to that exception put the exception handler in the catch block.

Why do JPA persistence exceptions extend from RuntimeException?

These exceptions mostly extend from HibernateException. However, if we're using Hibernate as a JPA persistence provider, these exceptions may get wrapped into PersistenceException. Both of these base classes extend from RuntimeException . Therefore, they're all unchecked. Hence, we don't need to catch or declare them at every place they're used.

What is the difference between JPA and hibernate?

Think of JPA as the guidelines that must be followed or an interface, while Hibernate's JPA implementation is code that meets the API as defined by the JPA specification and provides the under the hood functionality. In short, JPA is the interface while Hibernate is the implementation.

What is persistenceexception in hibernate?

These can be mapping errors, infrastructure problems, SQL errors, data integrity violations, session problems, and transaction errors. These exceptions mostly extend from HibernateException. However, if we're using Hibernate as a JPA persistence provider, these exceptions may get wrapped into PersistenceException.


1 Answers

HibernateException encapsulates the actual root cause than can provide you enough information for you to generate meaningful user-friendly messages. Read the Exception Handling section of their documentation.

like image 154
Aravind Yarram Avatar answered Nov 08 '22 02:11

Aravind Yarram