web項目數據源配置(普通配置和ssm框架下的配置)

一、無數據源連接池

一般情況下,如果不使用數據源連接池,我們是這樣獲取連接

Class.forName("com.mysql.jdbc.Driver"); //加載驅動

Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "199035"); //獲取連接


    然而每次進行數據庫操作的時候都要這樣獲取連接和釋放連接,不僅消耗資源,也要寫很多重複的代碼。所以現在都會使用連接池。


二、web項目配置數據源

<!-- 數據源配置 -->

1.首先要在 tomcatcontext中配置連接池

在context節點下配置

<!-- 持續掃描web.xml 文件更新數據源-->

<WatchedResource>WEB-INF/web.xml</WatchedResource>

<Resource

name="jdbc/TestWTY"

auth="Container"

type="javax.sql.DataSource"

maxActive="100" maxIdle="30" maxWait="10000"

username="root"

password="******"

driverClassName="com.mysql.jdbc.Driver"  

url="jdbc:mysql://localhost:3306/test"/>


2.在web.xml

<resource-ref>

      <description>DB Connection</description>

      <res-ref-name>jdbc/TestWTY</res-ref-name>

      <res-type>javax.sql.DataSource</res-type>

      <res-auth>Container</res-auth>

  </resource-ref>


3.獲取連接

在要進行數據庫操作的時候,先獲取連接

Context initCtx = new InitialContext();

Context envCtx = (Context) initCtx.lookup("java:comp/env");

//上面寫法都是不變的,下面這行中lookup中的字符串就是配置的JNDI名稱,

//比如context中的<resource name="xxx">或者web.xml中的<resource-env-ref-name>

DataSource ds = (DataSource)envCtx.lookup("jdbc/TestWTY");

Connection conn = ds.getConnection();


三、ssm框架下配置數據源

1.tomcat中配置數據源

步驟和二中(1)一樣

2.在項目中配置

applicationContext.xml文件中配置

<jee:jndi-lookup id="WTY" jndi-name="jdbc/TestWTY" />

 

<util:map id="dataSources">

    <entry key="WTY" value-ref="WTY" />

</util:map>

<!--構造器注入方式-->

<bean id="dataSourceLookup" class="org.springframework.jdbc.datasource.lookup.MapDataSourceLookup">

<constructor-arg>   

<ref bean="dataSources" />

</constructor-arg>

</bean>


<bean id="dataSource_center" class="util.dataSource.DynamicDataSource">

        <property name="targetDataSources" ref="dataSources" />

       <property name="dataSourceLookup" ref="dataSourceLookup" />

       <property name="defaultTargetDataSource" ref="WTY"/>

</bean>

數據庫連接的實現在mybatis中。




後面我會繼續補充細節


版權聲明:本文爲博主原創文章,未經博主允許不得轉載。

轉載請註明原文地址:https://blog.csdn.net/xyhh97/article/details/80014556



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章