JayPea
JayPea

Reputation: 9691

Spring: Catch ConstraintViolationException at commit time

I'm using Hibernate and Spring and I'm currently stuck with something which I thought would be very simple to fix. I have a service method similar to this:

@Transactional
public void deleteObject(ObjectClass object)
{
    this.objectClassDAO.delete(object);
}

I need to display a friendly message when the user tries to delete an object which is related to another entity. The problem I have is that the ConstraintViolationException is thrown until commit() is called, which runs outside of the scope of my service method. Is there a way to let spring call some intermediate code in the event of a particular exception, so that I can set the proper error message?

I've been searching on google for over an hour with no luck. The approaches I've found that seem at least mildly related seem like overkill and like they run at application level. Is there a simple way to intercept an exception after a commit at method-level?

Upvotes: 1

Views: 1690

Answers (1)

WA Hunt
WA Hunt

Reputation: 575

You're probably using FlushMode.AUTO and the exception is being thrown when the transaction ends (in the proxy around your service created by Spring). You can explicitly call Session.flush() inside of the objectClassDAO.delete() method. You typically don't want to do this, but in this case it will force a synchronization with the underlying persistence and if there is a constraint violation the exception will be thrown before objectClassDAO.delete returns. This may be a last resort though.

Upvotes: 2

Related Questions