1

In a Spring, JPA, Hibernate project I'm trying to get exception handling working. For the following code:

    @Repository("mscoutService")
    public class MScoutServiceImpl implements MScoutService, Serializable {

        @PersistenceContext
        private EntityManager em;

...
        @Override
        @Transactional
        public void deleteMission(Long missionId) {
            try {
                Mission mis = em.find(Mission.class, missionId);
                em.remove(mis);
            } catch (Exception e) {
                handle_exception();
            }
        }

I'm trying to catch underlying hibernate/jdbc/db exceptions (for example when dependent entities are still present the remove will fail with a org.springframework.orm.hibernate3.HibernateJdbcException) and perform some actions. However the catch code is never reached (checked in the debugger).

I guess this has to do with the way Spring manages this, but I don't know just how I can catch exceptions during em.remove()...

Any help is appreciated!

1 Answer 1

4

This is because the exception occurs when the session gets flushed. And perhaps it gets flushed when the transaction is committed - i.e. by the spring proxy. If you want to manually flush, you can use entityManager.flush().

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! adding em.flush() caused the exception handler to catch, so this solved my problem.
I know this thread is a little old, but would a better way be to handle the exception one layer above the repository where you are using @Transactional? Or is this the preferred way to handle exceptions?
yes, it's generally better to do that outside the repository.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.