Tom
Tom

Reputation: 1763

Spring EntityManager Hibernate Exception Handling

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!

Upvotes: 1

Views: 2085

Answers (1)

Bozho
Bozho

Reputation: 597076

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().

Upvotes: 4

Related Questions