`

数据源配置方式总结

 
阅读更多

数据源配置方式总结

 

/**

*数据源(mysqlsqlserveroracle+数据源信息配置(jndipropertiesxml)+数据源信息读取(jdbcspringhibernate)
*
本文件总结了mysql,sqlserver,oracle三种数据源的连接方式
*
其中包括SpringHibernate的连接方式
*
并通过属性文件、JNDI、配置文件三种方式进行连接
*/

一、通过属性文件读取数据源配置

1示例
--jdbc.properties
1
mysql
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncodeing=utf-8
jdbc.username=root
jdbc.password=123456

2)sqlserver
jdbc.driverClassName=net.sourceforge.jtds.jdbc.Driver
jdbc.url=jdbc:jtds:sqlserver://localhost:1433/test
jdbc.username=sa
jdbc.password=sa

3)oracle
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:orcale:thin://localhost:1521/nquser
jdbc.username=wapcms
jdbc.password=wapcms

 

 

 

--Spring-applicationContext-data.xml
<beans>
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName"
            value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>
    <!--
设定transactionManager -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
   
    <tx:annotation-driven/>
</beans>

2说明:DriverManagerDataSource建立连接是只要有连接就新建一个connection,根本没有连接池的作用。

Spring本身也提供了一个简单的数据源实现类DriverManagerDataSource ,它位于org.springframework.jdbc.datasource包中。这个类实现了javax.sql.DataSource接口,但它并没有提供池化连接的机制,每次调用getConnection()获取新连接时,只是简单地创建一个新的连接。因此,这个数据源类比较适合在单元测试或简单的独立应用中使用,因为它不需要额外的依赖类。
下面,我们来看一下DriverManagerDataSource的简单使用:当然,我们也可以通过配置的方式直接使用DriverManagerDataSource

java
代码

DriverManagerDataSource ds = new DriverManagerDataSource ();

ds.setDriverClassName("com.mysql.jdbc.Driver");

ds.setUrl("jdbc:mysql://localhost:3309/sampledb");

ds.setUsername("root");

ds.setPassword("1234");

Connection actualCon = ds.getConnection();

二、用JNDI 读取数据源server.xml

1、示例:1)mysql
<Resource name="jdbc/mysqlonline" type="javax.sql.DataSource"
    driverClassName="com.mysql.jdbc.Driver"
    password="123456"
    maxIdle="30"
    maxWait="10000"
    username="root"
    url="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=gb2312
    maxActive="100" />
2)orcale
<Resource name="jdbc/wapcms"  type="javax.sql.DataSource"
    driverClassName="oracle.jdbc.driver.OracleDriver"
    password="123456"
    maxIdle="30"
    maxWait="10000"
    username="root"
    url="jdbc:oracle:thin:@localhost:1521:nquser"
    maxActive="100"
    removeAbandoned="true"
    removeAbandonedTimeout="300"
    logAbandoned="true"/>
3)sqlserver
<Resource name="jdbc/user"  type="javax.sql.DataSource"
    driverClassName="net.sourceforge.jtds.jdbc.Driver"
    password="sa"
    maxIdle="30"
    maxWait="10000"
    username="sa"
    url="jdbc:jtds:sqlserver://localhost:1433/test"
    maxActive="100"
    removeAbandoned="true"
    removeAbandonedTimeout="300"
    logAbandoned="true"/>

<Host>
    <Context path="" docBase="E:/WAP/WAP_CMS/WebContent"
        debug="0" reloadable="true" privileged="true" crossContext="true"
        useNaming="true">
        <ResourceLink name="jdbc/wapcms" global="jdbc/wapcms" type="javax.sql.DataSource" />
        <ResourceLink name="jdbc/mysqlonline" global="jdbc/mysqlonline" type="javax.sql.DataSource" />
    </Context>
</Host>

--web.xml
<resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/wapcms</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

--Spring-application-data.xml
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName">
        <value>java:comp/env/jdbc/wapcms</value>
    </property>
</bean>
<!--
设定transactionManager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

2说明:通过jndi访问抽象的资源。这样程序不至于与访问的资源耦合。比如用jndi数据库密码变了与程序无关。不需要改代码

 

3、全局/非全局

1.全局数据源:

server.xml添加如下内容:

<Context path="/lizi" docBase="E:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\lizi"
        debug="5" reloadable="true" crossContext="true">

     <Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="sa" password="*******"
               driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"
               url="jdbc:sqlserver://localhost:1433;databaseName=frum"/>

</Context>

其中liziweb应用,前面的绝对地址,是应用放置的位置

name指定数据源在容器中的JNDI
   maxActive
指定数据源最大活动连接数。
   maxIdle
指定数据池中最大的空闲连接数。
  
maxWait指定数据池中最大等待获取连接的客户端。
   username
指定连接数据库的用户名。
  
password指定连接数据库的密码。
   driverClassName
指定连接数据库的驱动。
   url
指定数据库服务的URL

 

maxIdle,最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连
接将被标记为不可用,然后被释放。设为0表示无限制。
MaxActive,连接池的最大数据库连接数。设为0表示无限制。
maxWait ,最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示
无限制。

 

*maxActive:最大连接数据库连接数,设 0 为没有限制 
*maxIdle:最大等待连接中的数量,设 0 为没有限制 
*maxWait:最大等待毫秒数, 单位为 ms, 超过时间会出错误信息

 

一般把maxActive设置成可能的并发量就行了

 

maxActive、maxIdle和maxWait参数:

 


maxActive是最大激活连接数,这里取值为20,表示同时最多有20个数据库连 
 接。maxIdle是最大的空闲连接数,这里取值为20,表示即使没有数据库连接时依然可以保持20空闲的

 

连接,而不被清除,随时处于待命状态。MaxWait是最大等待秒钟数,这里取值-1,表示无限等待,直到

 

超时为止,也可取值9000,表示9秒后超时。

 

 

应用的WEB-INF下的web.xml添加如下内容(此处可以不添加)
<resource-ref>
用于指定对外部资源的引用声明
        <description>DB Connection</description>
        <res-ref-name>jdbc/mysqlx</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
      </resource-ref>

测试例子

<%@ page import="java.sql.*"%>
   <%@ page contentType="text/html;charset=GBK"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
<%@ page session="false" %>    
<%     
    DataSource ds = null;
    try{
    InitialContext ctx=new InitialContext();
    ds=(DataSource)ctx.lookup("java:comp/env/jdbc/mysql");  
   //java:comp/env/
这是固定的 jdbc/mysql这是前面配置取的jndi
    Connection conn = ds.getConnection();
    Statement stmt = conn.createStatement();   
    String strSql = " select * from message";

    ResultSet rs = stmt.executeQuery(strSql);
    while(rs.next()){
      String str= rs.getString("name");
     out.println("
数据:"+str);
   out.println("<br>");
      }  
    }
    catch(Exception ex){
        out.print("
错误信息是:"+ex.getMessage());
     ex.printStackTrace();
    }
%>

2.局部数据源

对于每个应用建立一个数据源,只需要将上面添加到server.xml中的内容单独建个文件即可。

在应用的META-INF文件夹下建立Context.xml将上面的内容考过来即可:(记住放在MET-INF下面)

<?xml version="1.0" encoding="GBK"?>
<Context path="/lizi" docBase="E:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\lizi"
        debug="5" reloadable="true" crossContext="true">

     <Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="sa" password="******"
               driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"
               url="jdbc:sqlserver://localhost:1433;databaseName=frum"/>

</Context>

三、用配置文件读取数据源信息

1、示例---hibernate.cfg.xml
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:ora</property>
        <property name="connection.username">koooso</property>
        <property name="connection.password">koooso</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">5</property>
        <!--
注意如果是运行在application中时,必须要有current_session_context_class这个属性,且值为

       thread
如果是运行在WEB服务器中则需要将值设置成jta。否则在运行时会报Exception

       in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured!
这个异常-->

       <property name="current_session_context_class">jta</property>


        <!--
Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>

        <mapping resource="com/chinamworld/hibernate/tf/MyTest.hbm.xml"/>

    </session-factory>

</hibernate-configuration>



 
---
sqlserver Spring
<bean id="dataSource"
   class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName"
    value="net.sourceforge.jtds.jdbc.Driver">
   </property>
   <property name="url"
    value="jdbc:jtds:sqlserver://localhost:1433/test">
   </property>
   <property name="username" value="sa"></property>
   <property name="password" value="admin"></property>
</bean>

<!--
Hibernate交由Spring管理(Hibernate相关配置信息) ,创建SessionFactory-->
<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.SQLServerDialect
     </prop>
     <prop key="hibernate.show_sql">true</prop>
    </props>
   </property>
   <property name="mappingResources">
    <list>
     <value>com/wuwei/struts/dao/User.hbm.xml</value>
    </list>
   </property>
</bean>

2xml 代码

view plaincopy to clipboardprint?

<!--[if !supportLists]-->1.   <!--[endif]--><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"

<!--[if !supportLists]-->2.   <!--[endif]-->destroy-method="close">

<!--[if !supportLists]-->3.   <!--[endif]--><property name="driverClassName" value="com.mysql.jdbc.Driver" />

<!--[if !supportLists]-->4.   <!--[endif]--><property name="url" value="jdbc:mysql://localhost:3309/sampledb" />

<!--[if !supportLists]-->5.   <!--[endif]--><property name="username" value="root" />

<!--[if !supportLists]-->6.   <!--[endif]--><property name="password" value="1234" />

<!--[if !supportLists]-->7.   <!--[endif]--></bean>


BasicDataSource
提供了close()方法关闭数据源,所以必须设定destroy-method=”close”属性, 以便Spring容器关闭时,数据源能够正常关闭。除以上必须的数据源属性外,还有一些常用的属性:
defaultAutoCommit
:设置从数据源中返回的连接是否采用自动提交机制,默认值为 true
defaultReadOnly
:设置数据源是否仅能执行只读操作, 默认值为 false
maxActive
:最大连接数据库连接数,设置为0时,表示没有限制;
maxIdle
:最大等待连接中的数量,设置为0时,表示没有限制;
maxWait
:最大等待秒数,单位为毫秒, 超过时间会报出错误信息;
validationQuery
:用于验证连接是否成功的查询SQL语句,SQL语句必须至少要返回一行数据, 如你可以简单地设置为:“select count(*) from user”
removeAbandoned
:是否自我中断,默认是 false
removeAbandonedTimeout
:几秒后数据连接会自动断开,在removeAbandonedtrue,提供该值;
logAbandoned
:是否记录中断事件, 默认为 false

C3P0
数据源
C3P0
是一个开放源代码的JDBC数据源实现项目,它在lib目录中与Hibernate一起发布,实现了JDBC3JDBC2扩展规范说明的 Connection Statement 池。C3P0类包位于/lib/c3p0/c3p0-0.9.0.4.jar。下面是使用C3P0配置一个 oracle数据源:

xml
代码

view plaincopy to clipboardprint?

<!--[if !supportLists]-->1.   <!--[endif]--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"

<!--[if !supportLists]-->2.   <!--[endif]-->destroy-method="close">

<!--[if !supportLists]-->3.   <!--[endif]--><property name="driverClass" value=" oracle.jdbc.driver.OracleDriver "/>

<!--[if !supportLists]-->4.   <!--[endif]--><property name="jdbcUrl" value=" jdbc:oracle:thin:@localhost:1521:ora9i "/>

<!--[if !supportLists]-->5.   <!--[endif]--><property name="user" value="admin"/>

<!--[if !supportLists]-->6.   <!--[endif]--><property name="password" value="1234"/>

<!--[if !supportLists]-->7.   <!--[endif]--></bean>


ComboPooledDataSource
BasicDataSource一样提供了一个用于关闭数据源的close()方法,这样我们就可以保证Spring容器关闭时数据源能够成功释放。
C3P0
拥有比DBCP更丰富的配置属性,通过这些属性,可以对数据源进行各种有效的控制:
acquireIncrement
:当连接池中的连接用完时,C3P0一次性创建新连接的数目;
acquireRetryAttempts
:定义在从数据库获取新连接失败后重复尝试获取的次数,默认为30
acquireRetryDelay
:两次连接中间隔时间,单位毫秒,默认为1000
autoCommitOnClose
:连接关闭时默认将所有未提交的操作回滚。默认为false
automaticTestTable
C3P0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数,那么属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将中为C3P0测试所用,默认为null
breakAfterAcquireFailure
:获取连接失败将会引起所有等待获取连接的线程抛出异常。但是数据源仍有效保留,并在下次调 用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试获取连接失败后该数据源将申明已断开并永久关闭。默认为 false
checkoutTimeout
:当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如设为0则无限期等待。单位毫秒,默认为0
connectionTesterClassName
: 通过实现ConnectionTesterQueryConnectionTester的类来测试连接,类名需设置为全限定名。默认为 com.mchange.v2.C3P0.impl.DefaultConnectionTester
idleConnectionTestPeriod
:隔多少秒检查所有连接池中的空闲连接,默认为0表示不检查;
initialPoolSize
:初始化时创建的连接数,应在minPoolSizemaxPoolSize之间取值。默认为3
maxIdleTime
:最大空闲时间,超过空闲时间的连接将被丢弃。为0或负数则永不丢弃。默认为0
maxPoolSize
:连接池中保留的最大连接数。默认为15
maxStatements
JDBC的标准参数,用以控制数据源内加载的PreparedStatement数量。但由于预缓存的Statement属于单个Connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素,如果maxStatements maxStatementsPerConnection均为0,则缓存被关闭。默认为0
maxStatementsPerConnection
:连接池内单个连接所拥有的最大缓存Statement数。默认为0
numHelperThreads
C3P0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能,通过多线程实现多个操作同时被执行。默认为3
preferredTestQuery
:定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个参数能显著提高测试速度。测试的表必须在初始数据源的时候就存在。默认为null
propertyCycle
: 用户修改系统配置参数执行前最多等待的秒数。默认为300
testConnectionOnCheckout
:因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的时候都 将校验其有效性。建议使用idleConnectionTestPeriodautomaticTestTable
等方法来提升连接测试的性能。默认为false
testConnectionOnCheckin
:如果设为true那么在取得连接的同时将校验连接的有效性。默认为false

 

3、注:这是一种推荐说明的数据源配置方式,它真正使用了连接池技术

四、小结
不管采用何种持久化技术,都需要定义数据源。Spring附带了两个数据源的实现类包,你可以自行选择进行定义。在实际部署时,我们可能会直接采用应用服务器本身提供的数据源,这时,则可以通过JndiObjectFactoryBeanjee命名空间引用JNDI中的数据源。

五、DBCPC3P0配置的区别:
C3PO

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">

<!--[if !supportLists]-->1.   <!--[endif]--><property name="driverClass">

<!--[if !supportLists]-->2.   <!--[endif]--><value>oracle.jdbc.driver.OracleDrivervalue>

<!--[if !supportLists]-->3.   <!--[endif]--></property>

<!--[if !supportLists]-->4.   <!--[endif]--><property name="jdbcUrl">

<!--[if !supportLists]-->5.   <!--[endif]--><value>jdbc:oracle:thin:@10.10.10.6:1521:DataBaseNamevalue>

<!--[if !supportLists]-->6.   <!--[endif]--></property>

<!--[if !supportLists]-->7.   <!--[endif]--><property name="user">

<!--[if !supportLists]-->8.   <!--[endif]--><value>testAdminvalue>

<!--[if !supportLists]-->9.   <!--[endif]--></property>

<!--[if !supportLists]-->10.  <!--[endif]--><property name="password">

<!--[if !supportLists]-->11.  <!--[endif]--><value>123456value>

<!--[if !supportLists]-->12.  <!--[endif]--></property>

<!--[if !supportLists]-->13.  <!--[endif]--></bean>


DBCP

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

<!--[if !supportLists]-->1.   <!--[endif]--><property name="driverClassName">

<!--[if !supportLists]-->2.   <!--[endif]--><value>oracle.jdbc.driver.OracleDrivervalue>

<!--[if !supportLists]-->3.   <!--[endif]--></property>

<!--[if !supportLists]-->4.   <!--[endif]--><property name="url">

<!--[if !supportLists]-->5.   <!--[endif]--><value>jdbc:oracle:thin:@10.10.10.6:1521:DataBaseNamevalue>

<!--[if !supportLists]-->6.   <!--[endif]--></property>

<!--[if !supportLists]-->7.   <!--[endif]--><property name="username">

<!--[if !supportLists]-->8.   <!--[endif]--><value>testAdminvalue>

<!--[if !supportLists]-->9.   <!--[endif]--></property>

<!--[if !supportLists]-->10.  <!--[endif]--><property name="password">

<!--[if !supportLists]-->11.  <!--[endif]--><value>123456value>

<!--[if !supportLists]-->12.  <!--[endif]--></property>

<!--[if !supportLists]-->13.  <!--[endif]--></bean>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics