Spring中 JdbcTemplate

db.properties

jdbc.user=root  
jdbc.password=root  
jdbc.driverClass=com.mysql.jdbc.Driver  
jdbc.jdbcUrl=jdbc:mysql:///spring  
  
jdbc.initPoolSize=5  
jdbc.maxPoolSize=10  

user 和 password 分别表示 mysql连接 的账号和密码。
driverClass 是加载的驱动。
jdbcUrl 是连接数据库的路径。格式是 jdbc:mysql://ip:port/数据库名(jdbc:mysql://localhost:3306/spring)
如果ip地址是本地,port是3306 是可以简写为 jdbc:mysql:///+数据库名。
initPoolSize 是 池内初始的数据连接个数,maxPoolSize是最大连接个数。和线程池是一样的概念。

applicationContext.xml
首先要指定导入的资源context:property-placeholder , location从类路径下加载外部属性文件db.properties。
配置一个c3p0的bean,和普通bean一样。只是赋值采用el表达式${}。再配置两个jdbc的模版bean就可以了。

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">  
      
    <!-- 导入资源文件 -->  
    <context:property-placeholder location="classpath:db.properties"/>  
      
    <!-- 配置 C3P0 数据源 -->  
    <bean id="dataSource"  
        class="com.mchange.v2.c3p0.ComboPooledDataSource">  
        <property name="user" value="${jdbc.user}"></property>  
        <property name="password" value="${jdbc.password}"></property>  
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>  
        <property name="driverClass" value="${jdbc.driverClass}"></property>  
  
        <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>  
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>  
    </bean>  
      
    <!-- 配置 Spirng 的 JdbcTemplate  -->  
    <bean id="jdbcTemplate"   
        class="org.springframework.jdbc.core.JdbcTemplate">  
        <property name="dataSource" ref="dataSource"></property>  
    </bean>  
      
    <!-- 配置 NamedParameterJdbcTemplate, 该对象可以使用具名参数,没有无参数的构造器,必须为其构造器指定参数 -->  
    <bean id="namedParameterJdbcTemplate"  
        class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">  
        <!-- NamedParameterJdbcTemplate 中含有带此参数的构造函数 -->
        <constructor-arg ref="dataSource"></constructor-arg>      
    </bean>
</beans> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值