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

版权声明:转载请注明原始链接 https://blog.csdn.net/sswqzx/article/details/83989607

在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的方式,注解用不了。

猜你喜欢

转载自blog.csdn.net/sswqzx/article/details/83989607