在服务类中正确使用Spring @Transaction

时间:2014-11-20 23:08:30

标签: java spring spring-data

我有一个从其他持久对象构建持久对象的类。稍微简化代码,首先是构建位置对象的方法:

@Transactional
private Location getLocation(PV1 pv1) {
    Ward wardObj = wardService.create(PV1Helper.getWard(pv1));  
    Location myLocation = new Location();
    myLocation.setWard(wardObj);

    return locationService.create(myLocation);
}

@Transactional
private Location getPriorLocation(PV1 pv1) {
    Ward wardObj = wardService.create(PV1Helper.getPriorWard(pv1));     
    Location myPriorLocation = new Location();
    myPriorLocation.setWard(wardObj);

    return locationService.create(myPriorLocation);
}

现在,我们有了一个方法(在一个不同的类中),它从位置对象中构建一个接纳对象并保留它:

@Transactional
public Admission transfer(MSH msh, PV1 pv1, PV2 pv2) {
    String visitNumber = pv1.getVisitNumber().getIDNumber().getValue();
    Visit myVisit = visitService.findByVisitNumber(visitNumber);        
    Admission myAdmission = admissionService.findByVisit(myVisit);

    if (myAdmission != null) {
        myAdmission.setLocation(getLocation(msh, pv1));
        myAdmission.setPriorLocation(getPriorLocation(msh, pv1));
    }
    else {
        log.warn("Unable to transfer visit number: {}.", visitNumber);
    }

    return myAdmission;
}

我注意到,有时添加到Admission对象的先前位置对象为null或实际上具有以下形式:foo.bar.Ward@7d26f3df否则代码有效。我突然意识到,当一个事务被关闭时,事务的对象 - 比如,先前的事件会丢失到会话中,因此当它被添加到另一个对象并坚持认为结果可能有点不确定时。它是否正确?也许我根本没有正确使用@Transactional?

我的服务类方法也有@Transactional:

@Transactional
public Ward create(Ward ward) {
    Ward created = ward;
    return unique(created);
}

@Transactional
private Ward unique(Ward ward) {
    Ward found = findByCode(ward.getCode());

    if (found == null) {
        return repository.save(ward);
    }
    return found;
}

交易经理

@Bean
public JpaTransactionManager transactionManager() {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(entityManagerFactory()
            .getObject());
    return transactionManager;
}

0 个答案:

没有答案