在Spring Boot应用中,有时候我们需要批量执行存储在数据库中的 SQL 脚本。本文将介绍一个实际的案例,演示如何通过 Spring Boot、MyBatis 和数据库来实现这一目标。
CREATE TABLE batchUpdate (
id INT AUTO_INCREMENT PRIMARY KEY,
update_type VARCHAR(255) NOT NULL,
success_flag BOOLEAN NOT NULL,
failure_count INT NOT NULL,
execution_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
sql_script TEXT NOT NULL
);
-- 第一条数据
INSERT INTO `batch_update` (`update_type`, `success_flag`, `failure_count`, `update_count`, `sql_script`)
VALUES
('update_type_1', 0, 0, 0,
'UPDATE batch_update SET success_flag = 1, update_count = update_count + 1 WHERE update_type = ''update_type_1'';
UPDATE batch_update SET success_flag = 1, update_count = update_count + 1 WHERE update_type = ''update_type_1'';
UPDATE batch_update SET failure_count = failure_count + 1, update_count = update_count + 1 WHERE update_type = ''update_type_1'';');
-- 第二条数据
INSERT INTO `batch_update` (`update_type`, `success_flag`, `failure_count`, `update_count`, `sql_script`)
VALUES
('update_type_2', 0, 0, 0,
'UPDATE batch_update SET success_flag = 1, update_count = update_count + 1 WHERE update_type = ''update_type_2'';
UPDATE batch_update SET success_flag = 1, update_count = update_count + 1 WHERE update_type = ''update_type_2'';
UPDATE batch_update SET failure_count = failure_count + 1, update_count = update_count + 1 WHERE update_type = ''update_type_2'';');
-- 第三条数据
INSERT INTO `batch_update` (`update_type`, `success_flag`, `failure_count`, `update_count`, `sql_script`)
VALUES
('update_type_1', 0, 0, 0,
'UPDATE batch_update SET success_flag = 1, update_count = update_count + 1 WHERE update_type = ''update_type_1'';
UPDATE batch_update SET success_flag = 1, update_count = update_count + 1 WHERE update_type = ''update_type_1'';
UPDATE batch_update SET failure_count = failure_count + 1, update_count = update_count + 1 WHERE update_type = ''update_type_1'';');
-- 第四条数据
INSERT INTO `batch_update` (`update_type`, `success_flag`, `failure_count`, `update_count`, `sql_script`)
VALUES
('update_type_2', 0, 0, 0,
'UPDATE batch_update SET success_flag = 1, update_count = update_count + 1 WHERE update_type = ''update_type_2'';
UPDATE batch_update SET success_flag = 1, update_count = update_count + 1 WHERE update_type = ''update_type_2'';
UPDATE batch_update SET failure_count = failure_count + 1, update_count = update_count + 1 WHERE update_type = ''update_type_2'';');
@RestController
@RequestMapping("/batchUpdate")
@AllArgsConstructor
public class BatchUpdateController {
private BatchUpdateService batchUpdateService;
@PostMapping("/executeScript/{updateType}")
public String executeScript(@PathVariable String updateType) {
List<BatchUpdateEntity> batchUpdateEntities = batchUpdateService.findByUpdateType(updateType);
if (batchUpdateEntities.isEmpty()) {
return "Update type not found.";
}
for (BatchUpdateEntity batchUpdateEntity : batchUpdateEntities) {
batchUpdateService.executeSqlScriptBatch(batchUpdateEntity);
}
return "SQL scripts executed successfully.";
}
}
javaCopy code
@Service
@AllArgsConstructor
public class BatchUpdateService {
private BatchUpdateMapper batchUpdateMapper;
public List<BatchUpdateEntity> findByUpdateType(String updateType) {
return batchUpdateMapper.findByUpdateType(updateType);
}
public void executeSqlScriptBatch(BatchUpdateEntity batchUpdateEntity) {
String sqlScript = batchUpdateEntity.getSqlScript();
List<String> sqlScripts = Arrays.stream(sqlScript.split(";"))
.map(String::trim)
.filter(s -> !s.isEmpty())
.toList();
System.out.println(sqlScripts.size());
sqlScripts.forEach(sql -> {
System.out.println("要执行的sql:" + sql);
batchUpdateMapper.executeSqlScript(sql);
System.out.println("已执行的sql:" + sql);
});
}
}
@Mapper
public interface BatchUpdateMapper {
List<BatchUpdateEntity> findByUpdateType(@Param("updateType") String updateType);
void executeSqlScript(@Param("sql") String sql);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lfsun.sqlscript.BatchUpdateMapper">
<resultMap id="BatchUpdateEntityResultMap" type="com.lfsun.sqlscript.BatchUpdateEntity">
<id property="id" column="id" />
<result property="updateType" column="update_type" />
<result property="successFlag" column="success_flag" />
<result property="failureCount" column="failure_count" />
<result property="executionTime" column="execution_time" />
<result property="sqlScript" column="sql_script" />
</resultMap>
<select id="findByUpdateType" resultMap="BatchUpdateEntityResultMap">
SELECT * FROM batch_update WHERE update_type = #{updateType}
</select>
<update id="executeSqlScript">
${sql}
</update>
</mapper>
通过这个案例,可以学到如何在 Spring Boot 中通过 MyBatis 实现批量执行 SQL 脚本的功能。在控制器层中,我们通过 @PostMapping
注解定义了一个接口,接收 updateType
作为路径参数,然后调用服务层的方法。服务层中,我们通过 MyBatis 执行 SQL 脚本,实现了对数据库的批量操作。