Spring框架中獲得DataSource物件的方法(轉)
阿新 • • 發佈:2019-02-06
在Spring框架中有如下3種獲得DataSource物件的方法:
一、從JNDI獲得DataSource
1.在tomcat伺服器中的配置示例,在tomcat目錄conf/context.xml檔案中新增:
<Resource name="jdbc/writeDataSource" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10" username="tysp" password="12345678" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@192.168.1.35:1521:orcl"/>
2.在resin伺服器中的配置示例,在resin目錄conf/resin.xml檔案中新增
<database jndi-name='jdbc/writeDataSource'> <driver type="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource"> <url>jdbc:mysql://localhost:3306/yfhesuanuseUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull</url> <user>root</user> <password>12345678</password> </driver> <prepared-statement-cache-size>8</prepared-statement-cache-size> <max-connections>30</max-connections> <max-idle-time>30s</max-idle-time> <connection-wait-time>30000</connection-wait-time> <transaction-timeout>30000</transaction-timeout> </database>
3.SpringJNDI資料來源配置資訊
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"> <value>java:comp/env/jdbc/writeDataSource</value> </property> </bean>
在賦值到value時必須加上"java:comp/env/"。
注意:記得要把資料庫驅動的jar包丟到伺服器的lib下。
二、從第三方的連線池獲得DataSource
要在Spring中使用DBCP連線池,需要引入commons-collections.jar、commons-dbcp.jar和commons-pool.jar。
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@192.168.1.35:1521:orcl"></property>
<property name="username" value="or_meal"></property>
<property name="password" value="or_meal"></property>
<property name="maxActive" value="100"></property>
<property name="maxIdle" value="30"></property>
<property name="maxWait" value="10"></property>
<property name="defaultAutoCommit" value="false"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect
</prop>
<prop key="show_sql">true</prop>
<prop key="format_sql">true</prop>
</props>
</property>
<property name="mappingResources">
<list></list>
</property>
</bean>
三、使用DriverManagerDataSource獲得DataSource
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver
</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@192.168.1.35:orcl
</value>
</property>
<property name="username">
<value>or_meal</value>
</property>
<property name="password">
<value>or_meal</value>
</property>
</bean>