Elegantly handling constraint violations in EJB/JPA environment?

后端 未结 2 743
有刺的猬
有刺的猬 2020-12-09 04:24

I\'m working with EJB and JPA on a Glassfish v3 app server. I have an Entity class where I\'m forcing one of the fields to be unique with a @Column annotation.



        
2条回答
  •  执念已碎
    2020-12-09 04:53

    I don't know how to detect the unique constraint violation in a portable way, the best I've come up with is just dealing with a PersistenceException. If someone can answer that I'd be interested too.

    I can help with the log issue.

    Inside of your persistence unit in your persistence.xml add the following:

    
      
    
    

    That will get rid of some of the exceptions. You'll still see stack traces where the container is seeing exceptions at CMT commit time. You have to swallow these before the container sees them. You can do the following.

    1) Create an application specific exception to indicate a persistence problem. I called mine DataStoreException.

    2) Don't use a no-interface view bean. Add the DataStoreException to the throws clause of the method signature in the biz interface.

    3) Add the following method to your EJB:

    @AroundInvoke
    public Object interceptor(InvocationContext ic) throws Exception {
        Object o = null;
        try {
            o = ic.proceed();
            if (!sessionContext.getRollbackOnly()) {
                entityManager.flush();
            }
        } catch (PersistenceException ex) {
            throw new DataStoreException(ex);
        }
        return o;
    }
    

提交回复
热议问题