springboot mybatis-plus运行sql前先运行其他sql的触发器
时间: 2023-09-05 16:08:11 浏览: 171
springboot+mybatis+mysql的配置
在Spring Boot项目中,如果需要在运行Mybatis-plus的SQL语句之前先运行其他SQL语句的触发器,可以通过在配置文件中配置SqlSessionFactoryBean来实现,具体步骤如下:
1. 创建一个类,实现ApplicationRunner接口,重写run方法,在该方法中执行需要先运行的SQL语句。
```java
@Component
public class SqlTriggerRunner implements ApplicationRunner {
@Autowired
private SqlSessionFactory sqlSessionFactory;
@Override
public void run(ApplicationArguments args) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
try {
sqlSession.update("update table1 set column1=value1 where id=1");
sqlSession.flushStatements();
sqlSession.commit();
} catch (Exception e) {
sqlSession.rollback();
throw e;
} finally {
sqlSession.close();
}
}
}
```
2. 在配置文件中配置SqlSessionFactoryBean,指定上面创建的SqlTriggerRunner类,并设置其执行顺序:
```yaml
mybatis-plus:
mapper-locations: classpath*:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
sqlSessionFactory:
typeAliasesPackage: com.example.demo.entity
mapperLocations: classpath*:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
default-executor-type: BATCH
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
before-init-script: classpath:/init.sql
# 指定SqlTriggerRunner执行顺序为最高,先执行
initializers:
- order: 0
object: com.example.demo.SqlTriggerRunner
```
在上面的配置文件中,我们指定了SqlTriggerRunner类,并设置其执行顺序为最高,即在所有初始化器中最先执行。这样,当项目启动时,就会先执行SqlTriggerRunner中的SQL语句,然后再执行其他的Mybatis-plus SQL语句。
阅读全文