spring中的JdbcTemplate---day04_01

JdbcTemplate的作用:
他就是用于和数据库交互的,实现对表的ceud操作
如何创建该对象·:
对象中的常用方法
我们来看看它最基本的使用:
先创建一个maven工程
在Java下新建包,在com.itheima.domain下新建一个Account实体类:

package com.itheima.domain;

import java.io.Serializable;

public class Account implements Serializable {
      private  Integer id;
      private  String name;
      private  Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

之后再新建一个JdbcTemplate包,在包下新建一个JdbcTemplate类,在里面我们运用它最基本的用法:

package com.itheima.kdbctemplate;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

/**
 * JdbcTemplate的最基本用法
 */
public class JdbcTemplateDemo1 {
    public static void main(String[] args) {
        //准备数据源,这里用spring的内置数据源
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/eesy");
        ds.setUsername("root");
        ds.setPassword("18205071");
        //1.1,创建JdbcTemplate对象
        JdbcTemplate jt = new JdbcTemplate();
        //1.2给jt设置数据源
          jt.setDataSource(ds);
        //2,执行操作
        jt.execute("insert into account(name,money)values ('ccc',1000)");
    }
}

运行结果:
在这里插入图片描述
可以看到它的基本使用是很简单的,但是我们可以看到我们把数据源写死了,我们还可以看到new的几个对象我们可以进行配置。
那么我们就需要在配置文件下新建一个bean.xml,并且在里面配置好数据源
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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--配置JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置数据源-->
    <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/eesy"></property>
        <property name="username" value="root"></property>
        <property name="password" value="18205071"></property>
    </bean>


</beans>

之后我们在jdbcTemplate包下再新建一个JdbcTemplate2类
在里面实现用配置的方式获取数据源执行代码:

package com.itheima.jdbctemplate;

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

/**
 * JdbcTemplate的最基本用法
 */
public class JdbcTemplateDemo2 {
    public static void main(String[] args) {
//        //准备数据源,这里用spring的内置数据源
//        DriverManagerDataSource ds = new DriverManagerDataSource();
//        ds.setDriverClassName("com.mysql.jdbc.Driver");
//        ds.setUrl("jdbc:mysql://localhost:3306/eesy");
//        ds.setUsername("root");
//        ds.setPassword("18205071");
//        //1.1,创建JdbcTemplate对象
//        JdbcTemplate jt = new JdbcTemplate();
//        //1.2给jt设置数据源
//        jt.setDataSource(ds);
//        //2,执行操作
//        jt.execute("insert into account(name,money)values ('cc',1000)");

        //获取容器
        ApplicationContext ac =new ClassPathXmlApplicationContext("bean.xml");
        //获取对象
        JdbcTemplate jd = ac.getBean("jdbcTemplate",JdbcTemplate.class);
        //执行操作
        jd.execute("insert into account(name,money)values ('cccc',1000)");
    }
}

我们可以看到运行结果,及数据库没有什么问题

在这里插入图片描述
在这里插入图片描述
我们在来看看crud操作:

package com.itheima.jdbctemplate;

import com.itheima.domain.Account;
import com.sun.corba.se.spi.resolver.LocalResolver;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * JdbcTemplate的最基本用法
 */
public class JdbcTemplateDemo3 {
    public static void main(String[] args) {

        //获取容器
        ApplicationContext ac =new ClassPathXmlApplicationContext("bean.xml");
        //获取对象
        JdbcTemplate jd = ac.getBean("jdbcTemplate",JdbcTemplate.class);
        //执行操作
        //jd.execute("insert into account(name,money)values ('cccc',1000)");
        //保存
      //  jd.update("insert into account(name,money)values (?,?)","eee",3333f);
        //更新
      //  jd.update("update  account set name = ?,money = ? where id = ?","test",4567,7);

        //删除
        jd.update("delete  from account where  id = ?",6);
        //查询所有
   //  List<Account> accounts =  jd.query("select * from account where money >?",new AccountRowMapper(),1000f );

//        List<Account> accounts =  jd.query("select * from account where money >?",new BeanPropertyRowMapper<Account>(Account.class),1000f );
//        for (Account account : accounts){
//         System.out.println(account);
//     }
     //查询一个
        List<Account> accounts =  jd.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),1 );

            System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));

        //查询返回一行一列
        Long count = jd.queryForObject("select count(*) from account where money > ?",Long.class,1000f);
        System.out.println(count);
    }
}
/**
 * 定义Account的封装策略
 */

class  AccountRowMapper implements RowMapper<Account> {

    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
        Account account = new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getFloat("money"));

        return account;
    }
}

当然我们在实际开发中是不这样写的,我们会在itheima包下新建一个dao包,在这下面新建接口和类编写代码:

IAccountDao接口

package com.itheima.dao;

import com.itheima.domain.Account;

/**
 * 账户的持久层接口
 */
public interface IAccountDao {
    /**
     * 根据id查询账户
     * @return
     */
    Account findAccountById(Integer integer);

    /**
     * 根据名称查询账户
     * @return
     */
    Account findAccountByName(String accountName);

    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);
}

AccountDaoImpl实现类

package com.itheima.dao.impl;

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

import java.util.List;

/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl implements IAccountDao {
    private JdbcTemplate jdbcTemplate;

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

    public Account findAccountById(Integer accountId) {
       List<Account> accounts =  jdbcTemplate.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 =  jdbcTemplate.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) {
jdbcTemplate.update("update account set name =?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
    }
}

我们来编写一下测试:
dbcTemplateDemo4

package com.itheima.jdbctemplate;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * JdbcTemplate的最基本用法
 */
public class JdbcTemplateDemo4 {
    public static void main(String[] args) {

        //获取容器
        ApplicationContext ac =new ClassPathXmlApplicationContext("bean.xml");

        IAccountDao accountDao = ac.getBean("accountDao",IAccountDao.class);
        Account account = accountDao.findAccountById(1);
        System.out.println(account);

    }
}

运行程序:
在这里插入图片描述
我们来看下项目目录:
在这里插入图片描述

之后我们来看个代码:
在这里插入图片描述
假如有多个实现类,这里就会出现多个重复性代码,那我们可以怎样修改呢,我们先cope一个AccountDaoImpl,改成AccountDaoImpl2,之后在Impl包下写一个类:JdbcDaoSupport,那么我们就可以让我们的dao实现类继承这个JdbcDaoSupport类

package com.itheima.dao.impl;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 此类用于抽取dao中的重复性代码
 */
public class JdbcDaoSupport {

    private JdbcTemplate jdbcTemplate;

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

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
}

之后我们修改一下·AccountDaoImpl:

package com.itheima.dao.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.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 =  super.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 =  super.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) {
        super.getJdbcTemplate().update("update account set name =?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
    }
}

可以看到我们之前的JdbcTemplate被换成了getJdbcTemplate(),这样我们就减少了重复性代码的出现。
那除了JdbcTemplate我们可以修改外,我们还可以在JdbcDaoSupport里修改DataSource:

package com.itheima.dao.impl;

import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * 此类用于抽取dao中的重复性代码
 */
public class JdbcDaoSupport {

    private JdbcTemplate jdbcTemplate;

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

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
    public  void  setDataSource(DataSource dataSource){
        if (jdbcTemplate == null){
            jdbcTemplate = createJdbcTemplate(dataSource);
        }
    }

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

之后我们去修改bean.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--配置账户的持久层-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
      <!--  <property name="jdbcTemplate" ref="jdbcTemplate"></property>-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置数据源-->
    <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/eesy"></property>
        <property name="username" value="root"></property>
        <property name="password" value="18205071"></property>
    </bean>


</beans>

运行一下:
在这里插入图片描述
可以看到没有问题。
我们来看下修改后的项目目录:
在这里插入图片描述
那这里我们之前说的dao实现类继承的JdbcDaoSupport类,JdbcDaoSupport这个类其实spring是自带的我们可以不用编写这个类,直接继承就可以了!!!!!!!!
那么我们自己写的,和spring自带的有什么区别呢?
区别就是:
在我们自己定义的JdbcTemplate上是可以加自动配置注解的,而自带的是不能加Aotuwired注解的,因为我们不能改变他的源码,他是只读属性的。
我们自己写的就可以基于xml配置和基于注解配置这两种方式。而使用spring自带的JdbcDaoSupport要想使用注解配置就有点麻烦了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值