提示:这是我的个人IT资源网站,所有资源都免费,注册登录后就可以看到密码,需要什么大家尽情选取!
如果我们想在项目启动的时候去执行一些sql脚本该怎么办呢,SpringBoot给我们提供了这个功能,可以在启动SpringBoot的项目时,执行脚本,下面我们来看一下。
我们先看一下源码
booleancreateSchema(){//会从application.properties或application.yml中获取sql脚本列表
List<Resource> scripts=this.getScripts("spring.datasource.schema",this.properties.getSchema(),"schema");if(!scripts.isEmpty()){if(!this.isEnabled()){
logger.debug("Initialization disabled (not running DDL scripts)");returnfalse;}
String username=this.properties.getSchemaUsername();
String password=this.properties.getSchemaPassword();//运行sql脚本this.runScripts(scripts, username, password);}return!scripts.isEmpty();}private List<Resource>getScripts(String propertyName, List<String> resources, String fallback){if(resources!= null){//如果配置文件中配置,则加载配置文件returnthis.getResources(propertyName, resources,true);}else{//指定schema要使用的Platform(mysql、oracle),默认为all
String platform=this.properties.getPlatform();
List<String> fallbackResources=newArrayList();//如果配置文件中没配置,则会去类路径下找名称为schema或schema-platform的文件
fallbackResources.add("classpath*:"+ fallback+"-"+ platform+".sql");
fallbackResources.add("classpath*:"+ fallback+".sql");returnthis.getResources(propertyName, fallbackResources,false);}}private List<Resource>getResources(String propertyName, List<String> locations,boolean validate){
List<Resource> resources=newArrayList();
Iterator var5= locations.iterator();while(var5.hasNext()){
String location=(String)var5.next();
Resource[] var7=this.doGetResources(location);int var8= var7.length;for(int var9=0; var9< var8;++var9){
Resource resource= var7[var9];//验证文件是否存在if(resource.exists()){
resources.add(resource);}elseif(validate){thrownewInvalidConfigurationPropertyValueException(propertyName, resource,"The specified resource does not exist.");}}}return resources;}
从源码观察,大致知道是什么意思了,SpringBoot默认会从类路径下去找脚本文件,但是类路径下只能放规定名称为schema或schema-platform的脚本文件,如果我们想要分好多个脚本文件,那么这种方式就不合适了,那么就需要我们在application.properties或application.yml中去配置脚本列表,那么这个初始化脚本操作能不能在配置文件中控制呢,可以的,有一个initialization-mode属性,可以设置三个值,always为始终执行初始化,embedded只初始化内存数据库(默认值),如h2等,never为不执行初始化。
spring:datasource:username: rootpassword: liuzhenyu199577url: jdbc:mysql://localhost:3306/jdbcdriver-class-name: com.mysql.cj.jdbc.Driverinitialization-mode: always
下面我们验证一下这两种方式,
- 默认放置schema或schema-platform的脚本文件
CREATETABLEIFNOTEXISTS department(IDVARCHAR(40)NOTNULL, NAMEVARCHAR(100),PRIMARYKEY(ID));
查看数据库没有department这个表,接下来我们启动程序
启动之后,我们再看一下,就执行了
- 配置文件中指定多个sql脚本
spring:datasource:username: rootpassword: liuzhenyu199577url: jdbc:mysql://localhost:3306/jdbcdriver-class-name: com.mysql.cj.jdbc.Driverinitialization-mode: alwaysschema:- classpath:department.sql- classpath:department2.sql- classpath:department3.sql
三个sql脚本都是插入语句
INSERTINTO department(ID,NAME)VALUES('1','2')INSERTINTO department(ID,NAME)VALUES('2','3')INSERTINTO department(ID,NAME)VALUES('3','4')
现在表中无任何数据,接下来我们启动程序
启动之后,我们再看一下,表中就有了三条数据
以上就是SpringBoot启动并初始化sql脚本的步骤