Spring 4.x 可以实现根据数据库脚本文件自动初始化数据库的配置,具体配置如下:
作者使用的数据库是MySQL
第一、将数据库脚本放入自定义的目录,我的目录如下:
demo.sql 和 log.sql是作者两个数据库的脚本文件
第二、在配置文件ApplicationContent.xml中增加如下配置:
<!-- 初始化数据库 (需要先手动创建好数据库) enabled=true/false 是否启用初始化 --> <jdbc:initialize-database data-source="mysqlDataSource" enabled="true"> <!-- 系统所用的数据库 --> <jdbc:script location="classpath:../db/demo.sql" /> <!-- 日志所用的数据库 --> <jdbc:script location="classpath:../db/log.sql" /> </jdbc:initialize-database>
mysqlDataSource是我的数据源配置如下:
<!-- mysql数据源配置 --> <bean id="mysqlDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <!-- 设置JDBC驱动名称 --> <property name="driverClass" value="${c3p0.driverClass}" /> <property name="jdbcUrl" value="${c3p0.url}" /> <property name="user" value="${c3p0.username}" /> <property name="password" value="${c3p0.password}" /> <property name="initialPoolSize" value="${c3p0.initialPoolSize}" /> <property name="maxPoolSize" value="${c3p0.maxPoolSize}" /> <property name="minPoolSize" value="${c3p0.minPoolSize}" /> <property name="acquireIncrement" value="${c3p0.acquireIncrement}" /> <property name="maxStatements" value="${c3p0.maxStatements}" /> <property name="preferredTestQuery" value="${c3p0.preferredTestQuery}" /> <property name="maxConnectionAge" value="${c3p0.maxConnectionAge}" /> <property name="testConnectionOnCheckout" value="${c3p0.testConnectionOnCheckout}" /> <property name="testConnectionOnCheckin" value="${c3p0.testConnectionOnCheckin}" /> <property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}" /> <property name="acquireRetryDelay" value="${c3p0.acquireRetryDelay}" /> <property name="breakAfterAcquireFailure" value="${c3p0.breakAfterAcquireFailure}" /> </bean>
注:使用jdbc标签的时候需要引入http://www.springframework.org/schema/jdbc,xml中的头文件如下红色字体部分:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oscache="http://www.springmodules.org/schema/oscache" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd">