1. 程式人生 > >Spring --14.Spring中Dao使用JdbcTemplate的二種方式

Spring --14.Spring中Dao使用JdbcTemplate的二種方式

在Dao中使用JdbcTemplate有二種方式:

(1)、直接Dao中宣告jdbcTemplate、通過set方法注入值

(2)讓Dao繼承JdbcDaoSupport

1、直接在Dao中宣告JdbcTemplate。通過set方法注入JdbcTemplate屬性的值

applicationContext.xml 把Dao配置到Spring中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">


    <!--引入jdbc.properties-->
    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"></property>
    </bean>

    //把Dao配置到Spring中
    <bean id="accountDao" class="com.day03.dao.Impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>


    <!--配置jdbc模板-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入資料-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>


        <!--配置資料來源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

</beans>

AccountDaoImpl.java  //編寫Dao注入JdbcTemplate

package com.day03.dao.Impl;

import com.day03.dao.AccountDao;
import com.day03.domain.Account;
import com.day03.romMapper.AccountRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;


/**
 * 建立AccountDaoImpl實現類,在其中宣告JdbcTemplate屬性,並提供set方法:
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 21:19 2018/11/14
 */

public class AccountDaoImpl implements AccountDao {
    //宣告JdbcTemplate屬性,並提供set方法。交給Spring容器
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 儲存使用者
     * @param account
     */
    @Override
    public void save(Account account) {
        this.jdbcTemplate.update("insert into account values(null,?,?)",account.getName(),account.getMoney());

    }

    /**
     * 更新使用者
     * @param account
     */
    @Override
    public void update(Account account) {
        this.jdbcTemplate.update("update account set name = ?, money = ?  where id = ? ;",account.getName(),account.getMoney(),account.getId());
    }

    /**
     * 根據id刪除使用者
     * @param id
     */
    @Override
    public void delete(Long id) {
        this.jdbcTemplate.update("delete from account where id = ?",id);
    }

    /**
     * 根據id查詢money
     * @param id
     */
    @Override
    public Double findMoney(Long id) {
        Double money = this.jdbcTemplate.queryForObject("select money from account where id = ?", Double.class, id);
        return money;
    }

    @Override
    public Account findById(Long id) {
        Account account = jdbcTemplate.queryForObject("select * from account where id = ?", new AccountRowMapper(),id);
        return account;
    }

    @Override
    public List<Account> findAll() {
        List<Account> list = jdbcTemplate.query("select * from account",new AccountRowMapper());
        return list;
    }
}

TestJdbcTemplate.java //測試

package com.day03.test;

import com.alibaba.druid.pool.DruidDataSource;
import com.day03.dao.AccountDao;
import com.day03.domain.Account;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.beans.PropertyVetoException;
import java.util.List;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 19:18 2018/11/14
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestJdbcTemplate {

    @Autowired
    private AccountDao accountDao;

    /**
     * 測試儲存資料
     */
    @Test
    public void test10(){
        Account account = new Account();
        account.setName("cisco1");
        account.setMoney(9999999999d);
        accountDao.save(account);
    }

    @Test
    public void test12(){
        Double money = accountDao.findMoney(4L);
        System.out.println("money = " + money);
    }
    /**
     * 查詢所有
     */
    @Test
    public void test11(){
        List<Account> all = accountDao.findAll();
        System.out.println("all = " + all);
    }
}

 

2、讓Dao繼承JdbcDaoSupport

讓AccountDaoImpl.java繼承JdbcDaoSupport

package com.day03.dao.Impl;

import com.day03.dao.AccountDao;
import com.day03.domain.Account;
import com.day03.romMapper.AccountRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.List;


/**
 * 建立AccountDaoImpl實現類,在其中宣告JdbcTemplate屬性,並提供set方法:
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 21:19 2018/11/14
 */

public class AccountDaoImpl2 extends JdbcDaoSupport implements AccountDao {
//    //宣告JdbcTemplate屬性,並提供set方法。交給Spring容器
//    private JdbcTemplate jdbcTemplate;
//
//    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
//        this.jdbcTemplate = jdbcTemplate;
//    }

    /**
     * 儲存使用者
     * @param account
     */
    @Override
    public void save(Account account) {
        this.getJdbcTemplate().update("insert into account values(null,?,?)",account.getName(),account.getMoney());

    }

    /**
     * 更新使用者
     * @param account
     */
    @Override
    public void update(Account account) {
        this.getJdbcTemplate().update("update account set name = ?, money = ?  where id = ? ;",account.getName(),account.getMoney(),account.getId());
    }

    /**
     * 根據id刪除使用者
     * @param id
     */
    @Override
    public void delete(Long id) {
        this.getJdbcTemplate().update("delete from account where id = ?",id);
    }

    /**
     * 根據id查詢money
     * @param id
     */
    @Override
    public Double findMoney(Long id) {
        Double money = this.getJdbcTemplate().queryForObject("select money from account where id = ?", Double.class, id);
        return money;
    }

    @Override
    public Account findById(Long id) {
        Account account = getJdbcTemplate().queryForObject("select * from account where id = ?", new AccountRowMapper(),id);
        return account;
    }

    @Override
    public List<Account> findAll() {
        List<Account> list = getJdbcTemplate().query("select * from account",new AccountRowMapper());
        return list;
    }
}

給Dao注入DataSource、不需要JdbcTemplate、因為繼承了JdbcDaoSupport這個類中已重寫了JdbcTemplate

applicationContext.xml

<?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:aop="http://www.springframework.org/schema/aop"
       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/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">


<!--引入jdbc.properties-->
    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"></property>
    </bean>
    <!--<context:property-placeholder location="classpath:jdbc.properties"/>-->

    <bean id="accountDao" class="com.day03.dao.Impl.AccountDaoImpl2">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--&lt;!&ndash;配置jdbc模板&ndash;&gt;-->
    <!--<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">-->
        <!--&lt;!&ndash;注入資料&ndash;&gt;-->
        <!--<property name="dataSource" ref="dataSource"></property>-->
    <!--</bean>-->

        <!--配置資料來源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

</beans>

TestJdbcTemplate.java測試類

package com.day03.test;

import com.alibaba.druid.pool.DruidDataSource;
import com.day03.dao.AccountDao;
import com.day03.domain.Account;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.beans.PropertyVetoException;
import java.util.List;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 19:18 2018/11/14
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext2.xml")
public class TestJdbcTemplate2 {

    @Autowired
    private AccountDao accountDao;

    /**
     * 測試儲存資料
     */
    @Test
    public void test10(){
        Account account = new Account();
        account.setName("cisco1");
        account.setMoney(9999999999d);
        accountDao.save(account);
    }

    @Test
    public void test12(){
        Double money = accountDao.findMoney(4L);
        System.out.println("money = " + money);
    }
    /**
     * 查詢所有
     */
    @Test
    public void test11(){
        List<Account> all = accountDao.findAll();
        System.out.println("all = " + all);
    }
}

JdbcDaoSupport.java原始碼

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.jdbc.core.support;

import java.sql.Connection;
import javax.sql.DataSource;
import org.springframework.dao.support.DaoSupport;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.SQLExceptionTranslator;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

public abstract class JdbcDaoSupport extends DaoSupport {
    @Nullable
    private JdbcTemplate jdbcTemplate;

    public JdbcDaoSupport() {
    }

    public final void setDataSource(DataSource dataSource) {
        if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) {
            this.jdbcTemplate = this.createJdbcTemplate(dataSource);
            this.initTemplateConfig();
        }

    }

    protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Nullable
    public final DataSource getDataSource() {
        return this.jdbcTemplate != null ? this.jdbcTemplate.getDataSource() : null;
    }

    public final void setJdbcTemplate(@Nullable JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
        this.initTemplateConfig();
    }

    @Nullable
    public final JdbcTemplate getJdbcTemplate() {
        return this.jdbcTemplate;
    }

    protected void initTemplateConfig() {
    }

    protected void checkDaoConfig() {
        if (this.jdbcTemplate == null) {
            throw new IllegalArgumentException("'dataSource' or 'jdbcTemplate' is required");
        }
    }

    protected final SQLExceptionTranslator getExceptionTranslator() {
        JdbcTemplate jdbcTemplate = this.getJdbcTemplate();
        Assert.state(jdbcTemplate != null, "No JdbcTemplate set");
        return jdbcTemplate.getExceptionTranslator();
    }

    protected final Connection getConnection() throws CannotGetJdbcConnectionException {
        DataSource dataSource = this.getDataSource();
        Assert.state(dataSource != null, "No DataSource set");
        return DataSourceUtils.getConnection(dataSource);
    }

    protected final void releaseConnection(Connection con) {
        DataSourceUtils.releaseConnection(con, this.getDataSource());
    }
}

 二個版本Dao的區別:

第一種在Dao類中定義JdbcTemplate的方式,適用於所有配置方式(xml和註解都可以)

第二種讓Dao繼承JdbcDaoSupport的方式,只能用於基於XML的方式,註解用不了。