引入Liquibase
<!-- LiquiBase是一个用于数据库重构和迁移的开源工具 --> <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> <version>4.2.0</version> </dependency>
2. 配置文件
具体关于LiquiBase的配置可以参考:
https://blog.csdn.net/a112626290/article/details/104263790
changelog-master.xml
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd"> <!-- changelog支持多种格式,主要有XML/JSON/YAML/SQL,推荐使用xml格式 --> <!-- 初始化最初的数据库 --> <include file="changelog/init_table.sql" relativeToChangelogFile="true"/> <include file="changelog/init_data.sql" relativeToChangelogFile="true"/> <!-- relativeToChangelogFile:用文件的相对路径而不是classpath --> <!-- 对数据库表的更改过程 --> <include file="changelog/table.xml" relativeToChangelogFile="true" /> <!-- 对视图的更改过程 --> <include file="changelog/view.xml" relativeToChangelogFile="true" /> <!-- 对数据的操作 --> <include file="changelog/data.xml" relativeToChangelogFile="true" /> </databaseChangeLog>
3.创建StartInitService
import java.sql.SQLException; import com.cxhd.rp.tool.Utils; import com.jfinal.kit.Prop; import com.jfinal.kit.PropKit; import com.jfinal.kit.StrKit; import com.jfinal.plugin.druid.DruidPlugin; import liquibase.Liquibase; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.LiquibaseException; import liquibase.resource.ClassLoaderResourceAccessor; import liquibase.resource.ResourceAccessor; public class StartInitService { private DruidPlugin druid; private String[] folders = { "health", "pacsio", "dcmrisen" }; private String[] dbUrlNames = { "jdbcUrl", "jdbcUrl1", "jdbcUrl2" }; public void init() { Prop p = PropKit.use("db.properties"); // 从对应的配置文件里面取数据 String activeConfig = PropKit.get("profiles.active"); if (!StrKit.isBlank(activeConfig)) { p.appendIfExists("db/db_" + activeConfig + ".properties", "utf-8"); } for (int i = 0; i < folders.length; i++) { druid = new DruidPlugin(p.get(dbUrlNames[i]), p.get("user"), p.get("password")); initDbConnection(folders[i]); } } /** * 初始化数据库连接 * * @return */ private void initDbConnection(String folderName) { druid.start(); ResourceAccessor clFO = new ClassLoaderResourceAccessor(); Liquibase liquibase = null; try { liquibase = new Liquibase("classpath:liquibase/" + folderName + "/changelog-master.xml", clFO, new JdbcConnection(druid.getDataSource().getConnection())); liquibase.update(""); } catch (LiquibaseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { liquibase.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } druid.stop(); } } }
4.启动配置,在config里面启动该初始化数据