在springboot中单独使用activeRecord并使用@Transactional事务
所需包
<!--jdbc start--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--jdbc end--> <!--引入JFinal的activerecord --> <dependency> <groupId>com.jfinal</groupId> <artifactId>activerecord</artifactId> <version>4.6</version> </dependency> <!-- activerecord end -->
其他包自己引入,如web包还有druid包等
配置文件
spring: datasource: #驱动类的名字 driverClassName: com.mysql.cj.jdbc.Driver #数据库url url: jdbc:mysql://127.0.0.1:3306/wx?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8 #账号 username: root #密码 password: 123456 #连接池类型 type: com.alibaba.druid.pool.DruidDataSource
详细配置自己添加
配置类
import javax.sql.DataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import com.alibaba.druid.pool.DruidDataSource; import com.jfinal.plugin.activerecord.ActiveRecordPlugin; import com.jfinal.plugin.activerecord.dialect.MysqlDialect; import com.jfinal.template.source.ClassPathSourceFactory; import com.xtsr.model._MappingKit; /** * @ClassName: DataSourceConfig.java * @Description: 数据库链接配置 * @version: v1.0.0 * @author: 小李子 * @date: 2019年10月28日 下午3:24:52 */ @Configuration public class DataSourceConfig { /** * 初始化连接池 * @return */ @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource druidDataSource() { return new DruidDataSource(); } /** * 设置数据源代理 */ @Bean public TransactionAwareDataSourceProxy transactionAwareDataSourceProxy() { TransactionAwareDataSourceProxy transactionAwareDataSourceProxy = new TransactionAwareDataSourceProxy(); transactionAwareDataSourceProxy.setTargetDataSource(druidDataSource()); return transactionAwareDataSourceProxy; } /** * 设置ActiveRecord */ @Bean public ActiveRecordPlugin activeRecordPlugin() { ActiveRecordPlugin arp = new ActiveRecordPlugin(transactionAwareDataSourceProxy()); arp.setDialect(new MysqlDialect()); arp.setShowSql(true); arp.getEngine().setSourceFactory(new ClassPathSourceFactory()); arp.addSqlTemplate("sql/all.sql"); _MappingKit.mapping(arp); arp.start(); return arp; } /** * 设置事务管理 */ @Bean public DataSourceTransactionManager dataSourceTransactionManager() { DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); dataSourceTransactionManager.setDataSource(transactionAwareDataSourceProxy()); return dataSourceTransactionManager; } }
启动类中开启事务
使用方法
访问报错
但是并没有添加到数据库
去掉事务注解
访问接口报同样的错,但是已经添加到数据库
证明事务配置成功
(*^_^*)