Search code examples
javajpaseam

Catch Exception at Transaction Commit in Seam


Everytime the user clicks the delete button to delete something, I call

em.remove(entity)

In case there are still referential constrains to this entity, I see an PersistenceException being thrown, and I can catch it to notice the user.

However, that is only for relationship that I can see in code. For example:

A has an OneToMany relationship to B

In a few special cases, the relationship is not reflected in code. For example:

Table A has a foreign key to Table B. But in code, there is no XtoX relationship between them

In these cases, I can't catch the PersistenceException mentioned above, which make the exception appears very ugly on the screen.

What I think is the exception appears at transaction commit time.

Is there anyway catch it?


Solution

  • In JPA, em.flush() method can used to catch the exception. After this operation is done, you will get the exception if you have the problem.

    For example:

    public void insert(Group group) {
        try {
            em.persist(group);
            em.flush();
        } catch (PersistenceException pe) {
    
        }
    }