存储过程(Stored Procedure)是在大型数据库系统中,一组为了完成特定功能的SQL 语句集,存储在数据库中,经过第一次编译后调用不需要再次编译,用户通过指定存储过程的名字并给出参数(如果该存储过程带有参数)来执行它。存储过程是数据库中的一个重要对象。
记录一下Spring JDBCTemplate 调用存储过程:
一、mysql创建存储过程(基于Navicat 视图软件):
1、右键表中函数,点击新建函数
2、点击过程
4、可以在文本中编辑自己的存储过程了:
BEGIN
DELETE FROM table1 where id=Key;
DELETE FROM table2 where id=Key;
DELETE FROM table3 where id=Key;
DELETE FROM table4 where id=Key;
END
二、首先配置mysql数据库,我这里用的是配置文件注入的方式:
@ConfigurationProperties(prefix = "masterdb")
@Component
@Data
public class MasterDbConfig {
String url;
String username;
String password;
}
application.propeities 中相对应数据:
masterdb.url=jdbc:mysql://10.10.10.10:3306/master
masterdb.username=mysql
masterdb.password=password
三、创建连接:
@Service
public class MasterDataSource extends JdbcTemplate {
private HikariDataSource dataSource;
@Autowired
MasterDbConfig config;
@PostConstruct
void init() {
dataSource = new HikariDataSource();
dataSource.setJdbcUrl(config.getUrl());
dataSource.setUsername(config.getUsername());
dataSource.setPassword(config.getPassword());
setDataSource(dataSource);
}
@PreDestroy
void close() {
close();
if (dataSource != null) {
dataSource.close();
}
}
}
四、创建方法执行存储过程,由于存储过程中有2个参数,所以第二个参数没有特别指定,就传了null
@Service
public class MasterDelService {
@Autowired
MasterDataSource masterDataSource;
public void deleteByKey(String key) {
masterDataSource.execute("call pro_clear_key('"+key+"',null)");
}
}
五、在controller层中注入 MasterDelService 类,其方法中调用 deleteByKey 的方法就完成了。
@Autowired
MasterDelService masterDelService;
@RequestMapping("deleteById")
public void deleteById(String id) {
masterDelService.deleteByKey(id);
}