Note that there are some explanatory texts on larger screens.

plurals
  1. POException Handling with JPA + Hibernate
    text
    copied!<p>I'm using JPA with Hibernate as the provider with container-managed transactions (JBoss AS 6.1.0.Final). </p> <p>I'm trying to implement some fine grained exception handling because I have a particular exception hierarchy on my app so I can define what to do in every situation. So, I've been investigating for hours and I find the documentation vague and the examples somewhat raw because exception handling is always left out "for the sake of clarity" or is a simple try-catch block that handles Exception e.</p> <p>For example, take this code:</p> <pre><code>public void deleteCompany(ICompany company) throws MyException1, MyException2 { if(entityManager != null){ if(company !=null) { try { ICompany companyReference= entityManager.getReference(Company.class, company.getId()); entityManager.remove(managedCompany); entityManager.flush(); } catch(EntityNotFoundException companyDoesNotExist) { //Wrap &amp; Throw } } else { throw new MyException1("An error occurred while attempting to save a null instance of a company"); } } else { throw new MyException2("The entity manager instance is null"); } } </code></pre> <p>The catch block is blank because that's where I'm stuck... I don't know which exception should I catch to alert the system that the user was attempting to delete a non-existent record.</p> <p>My concrete question is: Can I catch Hibernate exceptions on that catch block or do I have to catch the JPA ones? I found some sources that claim that JPA wraps the exceptions of the providers but that sounds odd to me. I've also found that calling the flush() method makes it possible to catch the database-access and manipulation exceptions, since the transactions are managed by the container and thus the commitment comes in further steps after invoking deleteCompany.</p> <p>Thank you.</p> <p><strong>EDIT:</strong> I'm wrapping the exceptions I catch with my own exceptions annotated with @ApplicationException(rollback=true), so I can throw them again and handle them more clearly.</p> <p><strong>EDIT 2:</strong> I've updated my code. The merge before the remove persists the company if it is not in the database, causing the remove to be successful everytime. Now the exceptions are being thrown and I'm testing how does it behave in different situations catching the JPA exceptions as suggested by Perception.</p> <p><strong>EDIT 3:</strong> Now it's working!, turns out the error was partially in my code because of that merge call. Getting the reference first and attempting a remove after does the trick, that way I was able to catch an EntityNotFoundException, wrap it and throw it again.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload