Spring框架中获得DataSource对象的方法(转)
在Spring框架中有如下3种获得DataSource对象的方法:
一、从JNDI获得DataSource
1.在tomcat服务器中的配置示例,在tomcat目录conf/context.xml文件中添加:
1: <Resource
2: name="jdbc/writeDataSource"
3: auth="Container"
4: type="javax.sql.DataSource"
5: maxActive="100"
6: maxIdle="30"
7: maxWait="10"
8: username="tysp"
9: password="12345678"
10: driverClassName="oracle.jdbc.driver.OracleDriver"
11: url="jdbc:oracle:thin:@192.168.1.35:1521:orcl"/>
2.在resin服务器中的配置示例,在resin目录conf/resin.xml文件中添加
1: <database jndi-name='jdbc/writeDataSource'>2: <driver type="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource">3: <url>jdbc:mysql://localhost:3306/yfhesuan?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull</url>4: <user>root</user>5: <password>12345678</password>6: </driver>7: <prepared-statement-cache-size>8</prepared-statement-cache-size>8: <max-connections>30</max-connections>9: <max-idle-time>30s</max-idle-time>10: <connection-wait-time>30000</connection-wait-time>11: <transaction-timeout>30000</transaction-timeout>12: </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>