Spring JdbcTemplate

1. Spring JdbcTemplate

1.1 JdbcTemplate概述

它是Spring框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装,Spring框架为我们提供了很多的操作模板类。例如:操作关系型数据库JdbcTemplate和HibernateTemplate,操作nosql数据库的RedisTemplate,操作消息队列的JmsTemplate等等。

1.2 JdbcTemplate开发步骤

  • 1、导入spring-jdbc和spring-tx坐标
  • 2、创建数据库表实体
  • 3、创建JdbcTemplate对象,设置数据源
  • 4、执行数据库操作

1. 导入依赖

之前springmvc的全部依赖也导进去了

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>

2. 创建实体类(我在test目录下建)

package com.abner.domain;

public class Account {

    private String name;
    private double money;

    public String getName() {
        return name;
    }

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

    public double getMoney() {
        return money;
    }

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

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

3. 创建测试类测试

关于JdbcTemplate的基本使用:https://blog.csdn.net/weixin_40001125/article/details/88538576

在JdbcTemplate中执行SQL语句的方法大致分为3类:

execute:可以执行所有SQL语句,一般用于执行DDL语句。
update:用于执行INSERT、UPDATE、DELETE等DML语句。
queryXxx:用于DQL数据查询语句。

package com.abner.test;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;

import java.beans.PropertyVetoException;

public class JdbcTemplateTest {

    //测试JdbcTemplate开发步骤
    @Test
    public void test1() throws PropertyVetoException {

        //创建数据源对象
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUser("root");
        dataSource.setPassword("root");

        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //设置数据源对象,知道数据库在哪(得有连接数据库的Connection对象)
        jdbcTemplate.setDataSource(dataSource);

        //执行操作
        //插入数据
        int row = jdbcTemplate.update("insert into  account values (?,?)", "zhangsan", 5000);//?为占位符执行成功返回1
        System.out.println(row);
    }
}

在这里插入图片描述
可以看到数据库表中已经成功插入
在这里插入图片描述

1.3 Spring产生JdbcTemplate对象

我们可以将JdbcTemplate的创建权交给Spring,将数据源DataSource的创建权也交给Spring,在Spring容器内部将数据源DataSource注入到JdbcTemplate模板对象中(又是熟悉的操作)。
Spring的核心是IOC(控制反转),即通过Spring帮我产生一个java bean对象。

1、resources目录下创建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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--dataSource和JdbcTemplate注入到容器中-->
    <!--数据源对象-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!--JdbcTemplate对象(Jdbc模板对象),将dataSource注入到JdbcTemplate中-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

2、测试

//测试Spring产生JdbcTemplate对象
@Test
public void test2(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    JdbcTemplate jdbcTemplate = applicationContext.getBean(JdbcTemplate.class);

    List<Map<String, Object>> query = jdbcTemplate.queryForList("select * from account");

    for(Map<String,Object> q : query){
        System.out.println(q);
    }
}

在这里插入图片描述

1.4 抽取配置文件

1、resources目录下创建jdbc.properties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=dbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

2、在applicationContext.xml添加Context命名空间并把外部properties文件加载进去

xmlns:context="http://www.springframework.org/schema/context"

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

在这里插入图片描述

<!--抽取配置文件-->
<!--加载外部properties文件-->
<context:property-placeholder location="jdbc.properties"/>
<!--数据源对象-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driver}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>
<!--JdbcTemplate对象(Jdbc模板对象),将dataSource注入到JdbcTemplate中-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
</bean>

3.测试

在这里插入图片描述

1.5 JdbcTemplate的常用操作(结合Spring集成Junit完成测试)

在这之前,要导入spring-test和Junit相关的依赖

1、修改操作

package com.abner.test;

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.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

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

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void testUpdate(){
        int result = jdbcTemplate.update("update account set money=10000 where name=?", "zhangsan");
        System.out.println(result);
    }

}

在这里插入图片描述

2、删除操作

@Test
public void testDelete(){
    int result = jdbcTemplate.update("delete from account where name=?", "赵六");
    System.out.println(result);
}

在这里插入图片描述

3、插入操作

 @Test
public void testInsert(){
    int result = jdbcTemplate.update("INSERT into account values (?,?)", "Tom",8888);
    System.out.println(result);
}

在这里插入图片描述

4、查询操作

查询全部
//查询全部
@Test
public void testQueryAll(){
    List<Account> accountList = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
    for(Account account : accountList){
        System.out.println(account);
    }
    System.out.println();
}

在这里插入图片描述

单个查询
//查询单个
@Test
public void testQueryOne(){
    Account account = jdbcTemplate.queryForObject("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), "Tom");
    System.out.println(account);
}

在这里插入图片描述

聚合查询
//聚合查询,查询总条数
@Test
public void testQueryCount(){
    Long count = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
    System.out.println(count);
}

在这里插入图片描述

1.5 JdbcTemplate知识要点

  • 1、导入spring-jdbc和spring-tx坐标
  • 2、创建数据库表实体
  • 3、创建JdbcTemplate对象
    • JdbcTemplate jdbcTemplate = new JdbcTemplate();
    • jdbcTemplate.setDataSource(dataSource);
  • 执行数据库操作
    • 更新操作
      • jdbcTemplate.update(sql, params)
    • 查询操作
      • jdbcTemplate.query(sql, Mapper, params)
      • jdbcTemplate.queryForObject(sql, Mapper, params)
      • jdbcTemplate.queryForObject(sql, requiredType)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值