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



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值