Spring @transactional注释用法

时间:2011-10-28 08:46:23

标签: spring transactional

如果我没有在limsservice审计metod上放置@Transactional注释,审计日志就不会持久化。但persistenceService中的persist metod已经完成了这个注释。为什么我必须把这个注释。

  @RequestMapping(value = "/lemf", method = RequestMethod.POST, headers = "Accept=application/json")
    public
    @ResponseBody
    Lemf create(HttpServletResponse response, @RequestBody Lemf lemf) {
        try {
            Lemf l = limsService.findLemfByName(lemf.getName());
            if (l == null) {
                     lemf=   limsService.addLemf(lemf);
                    limsService.audit("User action",getRequestInfo(),"New lemf created.");
                     return  lemf;
            }
            sendError(response, "Lemf Allready exist.");


        } catch (ProviderException e) {
            sendError(response, e);
        }
        return null;
    }


public class PersistenceServiceImpl implements PersistenceService {

   @Transactional(readOnly = false)
    public <T extends Persistable> T persist(T obj) {
        if (obj.getSystemId() != AbstractPersistable.UNSAVED_ID_VALUE) {
            log.info("Updating... :" + obj);
            T merged = em.merge(obj);
            return merged;
        } else {
            em.persist(obj);
            return obj;
        }
    }

}


public class LimsServiceImpl implements LimsService {
  @Override
    public Lemf addLemf(Lemf lemf) throws ProviderException {
        return  persistenceService.persist(lemf);
    }

    @Transactional
    public void  audit(String type,Pair<String,String >  pair,String log)  {
         auditService. audit("User action", pair, "New lemf created.");
    }

}

1 个答案:

答案 0 :(得分:1)

Spring参考章节10.5.6. Using @Transactional

对此非常明确:

  

提示

     

Spring建议您只使用@Transactional注释来注释具体类(以及具体类的方法),而不是注释接口。您当然可以将@Transactional注释放在接口(或接口方法)上,但这只能在您使用基于接口的代理时按预期工作。 Java注释不是从接口继承的事实意味着如果您使用基于类的代理(proxy-target-class =“true”)或基于编织的方面(mode =“aspectj”),那么事务设置是代理和编织基础设施无法识别,并且该对象不会被包含在事务代理中,这将是非常糟糕的。