Transaction and Rollback in Spring with JPA

混江龙づ霸主 提交于 2019-12-07 02:24:28
Tomasz Nurkiewicz

I don't know if I understand your question correctly, but your problem might be with ServiceDaoImpl exception handling:

try {
     em.persist(entity);
     em.flush();
} catch(Exception ex) {
     ex.printStackTrace();
}

This is a really bad practice (tm). Don't catch the exception but let it pop up from your method. This way:

  1. Transaction demarcation mechanism will intercept the exception and mark transaction as rollback only
  2. You won't ignore the exception (yes, catching and logging is almost as bad as swallowing)
  3. Very likely the exception will be caught at some higher level and logged properly (using SLF4J or similar) and you won't have this boilerplate.

So to cut long story short:

public class ServiceDaoImpl{

    @PersistenceContext (unitName="fb-persistence")
    private EntityManager em;

    @Transactional(readOnly=false)
    public void write(Service entity){
        em.persist(entity);
        em.flush();
    }

}

Note that you don't need setter for EntityManager and the field can be private.

Add a try catch block in your write method and throw an exception in case of error.

Put a rollbackFor or rollbackForClassname attribute in your @Transactional annotation for the exception that you rise, if you want to controll rollback events.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!