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是指明字符集。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM