Spring学习笔记03-JdbcTemplate

11 篇文章 0 订阅

Spring

什么是JdbcTemplate

JdbcTemplate是Spring框架中提供的一个对象,对原始的JDBC API进行简单封装,其用法与DBUtils类似。

JdbcTemplate对象的创建

  1. 配置数据源
  • JdbcTemplate对象在执行sql语句时也需要一个数据源,这个数据源可以使用C3P0或者DBCP,也可以使用Spring的内置数据源DriverManagerDataSource.

使用Spring内置的数据源DriverManagerDataSource.。在bean.xml里面配置

  <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/db_Spring?useUnicode=true&amp;characterEncoding=utf8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="52151"></property>
    </bean>
  1. 创建JdbcTemplate对象
    bean.xml里面创建
<!--配置JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
  1. JdbcTemplate的基本操作
package com.yll.jdbctemplate;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.sql.DatabaseMetaData;
import java.sql.DriverPropertyInfo;

/**
 * JdbcTemplate的最基本用法
 * */
public class JdbcTemplateDemo1 {
    public static void main(String[] args) {
        //1.获取容器
        ApplicationContext as = new ClassPathXmlApplicationContext("bean.xml");
        //2.获取对象
        JdbcTemplate jt = as.getBean("jdbcTemplate",JdbcTemplate.class);
        //3.执行操作
        jt.execute("insert into account(name,money)values('zczc',1312.1)");
    }
}

JdbcTemplate的增删改查操作

package com.yll.jdbctemplate;
/**
 * JdbcTemplate CRUD
 * */
public class JdbcTemplateDemo3 {
    public static void main(String[] args) {

        //1.获取容器
        ApplicationContext as = new ClassPathXmlApplicationContext("bean.xml");
        //2.获取对象
        JdbcTemplate jt = as.getBean("jdbcTemplate",JdbcTemplate.class);
        //3.执行操作
        //保存
        jt.update("insert into account(name,money)value(?,?)","eee",123.2);
        //更新
        jt.update("update account set name = ?,money = ? where id = ?","bbb",5135153.1,1006);
        //删除
        jt.update("delete from account where id = ?",1006);
        //查询所有
//        List<Account> accounts = jt.query("select * from account where money > ?",new AccountRowMapper(),10000f);
        List<Account> accounts = jt.query("select * from account where money > ?",new BeanPropertyRowMapper<Account>(Account.class),200000f);
        for (Account account :accounts){
            System.out.println(account);
        }
        //查询一个
        List<Account> accounts = jt.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),1001);
        System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));
        //查询返回一行一列(聚合查询)
        Long count = jt.queryForObject("select count(*) from account where money > ?",Long.class,10020f);
        System.out.println(count);
    }
}
/**
 * 定义Account的封装
 * */
class AccountRowMapper implements RowMapper<Account>{
    /**
     * 把结果集中的数据封装到Account中,然后由spring把每个Account加到集合中
     * */
    public Account mapRow(ResultSet rs, int i) throws SQLException {
        Account account = new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getFloat("money"));
        return account;
    }
}

关于查询操作

  • JdbcTemplate的查询操作使用其query()方法,其参数如下:

    • String sql: SQL语句
    • RowMapper<T> rowMapper: 指定如何将查询结果ResultSet对象转换为T对象.
    • @Nullable Object... args: SQL语句的参数

    其中RowMapper类类似于DBUtilsResultSetHandler类,可以自己写一个实现类,但常用Spring框架内置的实现类BeanPropertyRowMapper<T>(T.class)

  • 聚合查询
    执行聚合查询的方法为queryForObject()方法,其参数如下:

    • String sql: SQL语句
    • Class<T> requiredType: 返回类型的字节码
    • @Nullable Object... args: SQL语句的参数

在Dao层直接使用JdbcTemplate

在Dao层使用JdbcTemplate,需要给Dao注入JdbcTemplate对象

package com.yll.dao.impl;

import com.yll.dao.IAccountDao;
import com.yll.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {


    public Account findAccountById(Integer accountId) {
        List<Account> accounts = getJdbcTemplate().query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
        return accounts.isEmpty()?null:accounts.get(0);
    }

    public Account findAccountByName(String accountName) {
        List<Account> accounts = getJdbcTemplate().query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
        if(accounts.isEmpty()){
            return null;
        }
        if(accounts.size()>1){
            throw new RuntimeException("结果集不唯一");
        }
        return accounts.get(0);
    }

    public void updateAccount(Account account) {
        getJdbcTemplate().update("update account set name = ?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
    }
}

JdbcDaoSupport类 自己写的

package com.yll.dao.impl;

import org.springframework.jdbc.core.JdbcTemplate;

public class JdbcDaoSupport {
    private JdbcTemplate jdbcTemplate;

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

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
}

在Dao层对象继承JdbcDaoSupport类

在实际项目中,我们会创建许多DAO对象,若每个DAO对象都注入一个JdbcTemplate对象,会造成代码冗余.

  • 实际的项目中我们可以让DAO对象继承Spring内置的JdbcDaoSupport类.在JdbcDaoSupport类中定义了JdbcTemplateDataSource成员属性,在实际编程中,只需要向其注入DataSource成员即可,DataSourceset方法中会注入JdbcTemplate对象.
  • DAO的实现类中调用父类的getJdbcTemplate()方法获得JdbcTemplate()对象.

bean.xml中,我们只要为DAO对象注入DataSource对象即可,让JdbcDaoSupport自动调用JdbcTemplateset方法注入JdbcTemplate

<?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">

	<!-- 配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/数据库名"></property>
        <property name="username" value="用户名"></property>
        <property name="password" value="密码"></property>
    </bean>

    <!-- 配置账户的持久层-->
    <bean id="accountDao" class="com.java.dao.impl.AccountDaoImpl">
        <!--不用我们手动配置JdbcTemplate成员了-->
        <!--<property name="jdbcTemplate" ref="jdbcTemplate"></property>-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

</beans>

在实现DAO接口时,我们通过super.getJdbcTemplate()方法获得JdbcTemplate对象.

public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
    
    @Override
    public Account findAccountById(Integer id) {
		//调用继承自父类的getJdbcTemplate()方法获得JdbcTemplate对象
        List<Account> list = getJdbcTemplate().query("select * from account whereid = ? ", new AccountRowMapper(), id);
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public Account findAccountByName(String name) {
        //调用继承自父类的getJdbcTemplate()方法获得JdbcTemplate对象
        List<Account> accounts = getJdbcTemplate().query("select * from account wherename = ? ", new BeanPropertyRowMapper<Account>(Account.class), name);
        if (accounts.isEmpty()) {
            return null;
        } else if (accounts.size() > 1) {
            throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
        }
        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
		//调用继承自父类的getJdbcTemplate()方法获得JdbcTemplate对象
        getJdbcTemplate().update("update account set money = ? where id = ? ", account.getMoney(), account.getId());
    }
}

但是这种配置方法存在一个问题: 因为我们不能修改JdbcDaoSupport类的源代码,DAO层的配置就只能基于xml配置,而不再可以基于注解配置了.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值