首页 > 其他分享 >org.springframework.dao.InvalidDataAccessApiUsageException: no transaction is in progress

org.springframework.dao.InvalidDataAccessApiUsageException: no transaction is in progress

时间:2022-10-09 10:08:37浏览次数:62  
标签:事务 transaction 管理器 no dao springframework PlatformTransactionManager import org


  关注这个问题,是因为我们的项目在使用jpa 和sharding分库分表以后,在跑test类的时候,save保存不进去数据,但是不报任何错。然后我把save改成saveAndFlush的时候,开始报这个错了。注意在service层已经加过@Transactional 注解了。 如果搜这个问题的,多数是因为没加@Transactional注解。

  没加sharding分库分表,是没问题的,能插进去数据。事务都用的好好的。但是加了sharing以后插入不进去数据了,然后只能通过启动项目调用 controller 才行。但是在定时任务里边去跑,也插入不进去数据。把save改成 saveAndFlush 就报一个错误,报的是没有事务的错误。

  于是就很费解了,我明明加了@transactional 注解了,为啥到了执行这一行,他就报没有事务呢?

  所以就查到 事务管理器上来了。


# # 先说下,如何在springboot中查看事务管理器

org.springframework.dao.InvalidDataAccessApiUsageException: no transaction is in progress_事务管理

@Bean
public Object testBean(PlatformTransactionManager platformTransactionManager){
System.out.println(">>>>>>>>>>>"+platformTransactionManager.getClass().getName());
return new Object();
}

  启动项目,然后在控制台上就可以看到:

 

org.springframework.dao.InvalidDataAccessApiUsageException: no transaction is in progress_spring_02

 

# # 查这个是为了查看为什么我明明添加了@Transactional 注解,但是还是报错

 报这个错:

  org.springframework.dao.InvalidDataAccessApiUsageException: no transaction is in progress; nested exception is javax.persistence.TransactionRequiredException: no transaction is in progress
  可能你看到个错误,会觉得是 没有添加@Transaction注解,但是我明明已经在service层添加过了。

 

# #  最后解决方案就是 

  更换一下事务管理器,通过添加一个配置类,就可以替换了。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;

/**
* @author angus
* @create 2020-03-28 20:21
*/
@Configuration
public class TransactionManagerConfig implements TransactionManagementConfigurer {
@Resource(name="transactionManager")
private PlatformTransactionManager txManager;

// // 创建事务管理器1
// @Bean(name = "txManager1")
// public PlatformTransactionManager txManager(DataSource dataSource) {
// return new DataSourceTransactionManager(dataSource);
// }

// 创建事务管理器
@Bean(name = "transactionManager")
public PlatformTransactionManager txManager(EntityManagerFactory factory) {
return new JpaTransactionManager(factory);
}

//其返回值代表在拥有多个事务管理器的情况下默认使用的事务管理
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return txManager;
}

}

 

# # 然后 问题解决了

标签:事务,transaction,管理器,no,dao,springframework,PlatformTransactionManager,import,org
From: https://blog.51cto.com/u_15812686/5739731

相关文章