jdbc:initialize-database标签的研究

在spring的applicationContext.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:jdbc="http://www.springframework.org/schema/jdbc"-->xmlns中引入这个
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
           http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/jdbc---------------------------------->xsi:schemaLocation中引入这个
        http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd-------->xsi:schemaLocation中引入这个
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.2.xsd">
</beans>
总体来说就是引入了jdbc的schema。那么我们就可以用jdbc标签了,本文只说<jdbc:initialize-database>标签。
先给一个例子,再借例子加以说明。
例子:
<jdbc:initialize-database data-source="dataSource" ignore-failures="NONE" enabled="${jdbc.initializedatabase}">
<jdbc:script encoding="utf-8" location="/WEB-INF/db-init.sql"/>
</jdbc:initialize-database>


jdbc:initialize-database这个标签的作用是在工程启动时,去执行一些sql,也就是初始化数据库。比如向数据库中建立一些表及插入一些初始数据等。这些sql的路径需要在其子标签jdbc:script中去指定。
1.jdbc:initialize-database标签
a.dataSource不用说,要引一个配置好的数据源。
b.ignore-failures有三个值:NONE,DROPS,ALL,设置为NONE时,不忽略任何错误,也就是说,当sql执行报错时服务启动终止。设置为DROPS时,忽略删除错误,如当sql中有一个删除表drop table d_area的sql,而d_area表不存在,此时这个错误会被忽略。设置为ALL时,忽略任何错误。
c.enabled是用来表明初始化数据库是否执行。这个很有用,一般初始化一次就够了,第二次以后就没必要了,除了特殊情况。这个enabled的值是一个boolean值。设置方法有三。一是直接写true或false;二是根据配置文件某个值来设置,本文用的是这个。
<bean id="propertyPlaceholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>WEB-INF/db.properties</value>
</list>
</property>
</bean>


设置enabled="${jdbc.initializedatabase}"后,会到properties中去获取key为jdbc.initializedatabase的值。三是这样设置:enabled="#{systemProperties.INITIALIZE_DATABASE}",这样设置后,会到你所设置的dataSource中去找property名字为systemProperties.INITIALIZE_DATABASE的值或prop key为systemProperties.INITIALIZE_DATABASE的值。
2.jdbc:initialize-database这个标签必需要至少包含一个<jdbc:script>,这个标签是来指定你要初始化数据库的sql的路径。如:location="/WEB-INF/db-init.sql"/;location="classpath:com/sql/db-init.sql"。encoding是指明字符集。

原文地址:https://www.cnblogs.com/adolfmc/p/3570824.html