spring配置文件中jdbc:initialize-database标签的研究

在spring的applicationContext.xml中若是引入了:
<beans xmlns="http://www.springframework.org/schema/beans" 
		xmlns:sec="http://www.springframework.org/schema/security"
		xmlns:task="http://www.springframework.org/schema/task"
		xmlns:aop="http://www.springframework.org/schema/aop" 
		xmlns:context="http://www.springframework.org/schema/context" 
		xmlns:jee="http://www.springframework.org/schema/jee" 
		xmlns:tx="http://www.springframework.org/schema/tx" 
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		xmlns:jdbc="http://www.springframework.org/schema/jdbc"
		xsi:schemaLocation="http://www.springframework.org/schema/aop 
			http://www.springframework.org/schema/aop/spring-aop-4.0.xsd         
			http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans-4.0.xsd         
			http://www.springframework.org/schema/context 
			http://www.springframework.org/schema/context/spring-context-4.0.xsd         
			http://www.springframework.org/schema/jee 
			http://www.springframework.org/schema/jee/spring-jee-4.0.xsd         
			http://www.springframework.org/schema/tx 
			http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
			http://www.springframework.org/schema/task 
			http://www.springframework.org/schema/task/spring-task-4.0.xsd
        	http://www.springframework.org/schema/jdbc
        	http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd">



        整体来讲就是引入了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是指明字符集。 spring

相关文章
相关标签/搜索