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



猜你喜欢

转载自blog.csdn.net/xyhh97/article/details/80014556
今日推荐