2014-10-06 96 views
0

我在我的项目中使用spring jpa事务。一个案例包括在同步方法中插入数据,以及另一个线程访问数据时未更新数据。我的代码如下:@transactional在春天jpa不更新表

public UpdatedDTO parentMethod(){ 
    private UpdatedDTO updatedDTO = getSomeMethod(); 
    childmethod1(inputVal); 
    return updatedDTO; 
} 

@Transactional 
public synchronized childmethod1(inputVal){ 
//SomeCodes 

//Place where update takes place 
TableEntityObject obj = objectRepository.findByInputVal(inputVal); 
if(obj == null){ 
    childMethod2(inputVal); 
    } 

} 

@Transactional 
public void childMethod2(inputVal){ 

//Code for inserting 
TableEntityObject obj = new TableEntityObject(); 
obj.setName("SomeValue"); 
obj.setValueSet(inputVal); 
objectRepository.save(obj); 
} 

现在,如果两个线程同时访问,并且如果第一线程完成childmethod2和childmethod1和没有后完成parentMethod()如果第二线程说到childMethod1(),并且如果存在数据的检查,该数据为空并没有通过第一线更新。我已经尝试了很多方法,如

@Transactional(propagation = Propagation.REQUIRES_NEW) 
public synchronized childmethod1(inputVal){ 
//SomeCodes 

//Place where update takes place 
TableEntityObject obj = objectRepository.findByInputVal(inputVal); 
if(obj == null){ 
    childMethod2(inputVal); 
    } 

} 

@Transactional(propagation = Propagation.REQUIRES_NEW) 
public void childMethod2(inputVal){ 

//Code for inserting 
TableEntityObject obj = new TableEntityObject(); 
obj.setName("SomeValue"); 
obj.setValueSet(inputVal); 
objectRepository.save(obj); 
} 

也试图在childMethod1()中取消@transactional,但没有任何结果。我知道我在这里做错了什么,但无法弄清楚我在哪里做错了什么。可以帮我解决这个问题

+0

为什么你的方法同步和事务? – 2014-10-06 11:42:45

回答

0

@Transactional在spring beans上使用代理来解析。这意味着如果你的@Transactional方法是从同一个类中调用的,它将不起作用。看看Spring @Transaction method call by the method within the same class, does not work?

最简单的方法就是将这些方法转换为单独的服务。

+0

我已经删除了@transactional中的childmethod1并将childmethod2()移动到了另一个类中。但是它没有得到更新 – user2078883 2014-10-06 12:55:53

+0

如果childmethod1是第一个调用的方法,它将不起作用。调用的第一个方法必须是带注释的方法。 – uaiHebert 2014-10-07 00:44:21

0

典型的清单,我跟随的情况下这样的:

  1. 如果基于Java的配置,那么要确保 @EnableTransactionManagement annocation是存在于含有@Configuration注释
  2. 确保transactionManager的bean是类 创建,这应该在配置类中提及。
  3. 使用在其上调用库,通常在DAO层
  4. 添加针对其调用在存储库

尼斯的方法的类的@Service注释的类中的方法@Transactional annocatio的博客,它解释了交易配置与JPA的深度 - >http://www.baeldung.com/2011/12/26/transaction-configuration-with-jpa-and-spring-3-1/68954