天天看點

使用Spring配置資料源JdbcTemplate

c3p0作為示範

1.編寫資源檔案(db.properties)

jdbc.user=root
jdbc.password=root
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/spring
jdbc.driverClass=com.mysql.jdbc.Driver      

2.在SpringXML配置中擷取資料源資源檔案

<context:property-placeholder location="classpath:db.properties"/>      

3.配置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>
    </bean>      

4.配置spring的jdbcTemplale bean

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>    
 </bean>      

到這裡資料源已經配置好了,直接擷取bean就可以使用了。

案例:

修改前的資料:

修改後的資料:

操作代碼:

ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) ac.getBean("jdbcTemplate");
String sql = "update tb_student set name='lisi' where id=2 ";
jdbcTemplate.update(sql);      

其他的操作和原生jdbc沒什麼太大差別。

配置NamedParameterJdbcTemplate隻需要通過構造注入dataSource就OK

<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
      <constructor-arg ref="dataSource"></constructor-arg>
</bean>      
NamedParameterJdbcTemplate jdbcTemplate = (NamedParameterJdbcTemplate)                 
        ac.getBean("namedParameterJdbcTemplate");
        String sql = "update tb_student set name=:name where id=:id ";
        Map<String, Object> map = new HashMap();
        map.put("name","lisi2");
        map.put("id",2);
        jdbcTemplate.update(sql, map);      

學習是永無止境的。