【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对象

JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);

  1. 执行数据库操作
    @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("123456");
//          创建JdbcTemplate对象
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
//          设置数据源对象   告诉jJdbcTemplate对象数据库在哪
        jdbcTemplate.setDataSource(dataSource);
//          执行操作
        jdbcTemplate.update("insert into student values(?,?,?)", 1,"zhangsan", 5000);

1.3 Spring产生JdbcTemplate对象

我们可以将JdbcTemplate的创建权交给Spring,将数据源DataSource的创建权也交给Spring,在Spring容器内部将数据源DataSource注入到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"
       xmlns:context="http://www.springframework.org/schema/context"
       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
">
<!--    加载jdbc。properties文件-->
    <context:property-placeholder location="classpath: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对象     -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--       设置jdbcTemplate对象数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

从Spring容器当中获取JdbcTemplate对象进行操作

    @Test
//    测试Spring产生JdbcTemplate对象
    public void test2() throws PropertyVetoException {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
//      获取JdbcTemplate对象
        JdbcTemplate jdbcTemplate = app.getBean(JdbcTemplate.class);
//       执行操作
        jdbcTemplate.update("insert into student values(?,?,?)", 3, "老六", 250);
    }

1.4 JdbcTemplate的常用操作

查询操作

package test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import zking.entity.Accunt;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
//加载配置文件
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {
//  根据类型依赖注入
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Test
    public void queryAccount() {
        /**
         * 查询单个
         */
        Student student= jdbcTemplate.queryForObject("select * from student where id=?", new BeanPropertyRowMapper<Student>(Student.class), 1);
        System.out.println(accunt);
    }
    @Test
    public void aggregationQuery() {
        /**
         * 聚合函数查询
         */
        Long aLong = jdbcTemplate.queryForObject("select count(*) from student", Long.class);
        System.out.println(aLong);
    }
    @Test
    public void queryAll() {
        /**
         *查询所有
         */
        List<Student> studentList = jdbcTemplate.query("select * from student where id=?", new BeanPropertyRowMapper<Student>(Student.class),1);
        System.out.println(accuntList);
    }

更新操作

    @Test
    public void update() {
        //修改
            jdbcTemplate.update("update student set money=? where id=?", 100000, 2);
    }
    @Test
    public void delete(){
        //删除
        jdbcTemplate.update("delete from student where id=?",3);
    }
    @Test
    public void insert(){
        //增加
        jdbcTemplate.update("insert into student values(?,?,?)", 1,"zhangsan", 5000);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringJdbcTemplateSpring框架对JDBC进行封装的一个工具类,旨在使JDBC更加易于使用JdbcTemplate处理了资源的建立和释放,帮助我们避免一些常见的错误,比如忘记关闭连接。使用JdbcTemplate可以简化数据库操作的代码量,并提供了一些便捷的方法来执行数据库查询、更新等操作。 使用JdbcTemplate的步骤如下: 1. 引入相关的jar包,包括druid-1.1.9.jar、spring-jdbc-5.2.6.RELEASE.jar、spring-orm-5.2.6.RELEASE.jar和spring-tx-5.2.6.RELEASE.jar。这些jar包提供了JdbcTemplate的实现和相关依赖。 2. 在Spring的配置文件中添加数据库连接的配置,包括数据库的URL、用户名、密码和驱动类名等信息。这可以通过配置一个DataSource对象来实现。 3. 配置JdbcTemplate对象,将DataSource对象注入到JdbcTemplate中。可以通过在Spring的配置文件中定义一个JdbcTemplate的bean,并设置其dataSource属性为前面配置的DataSource对象。 4. 创建service和dao对象,将JdbcTemplate对象注入到dao中。在dao层的代码中,可以通过在dao类中定义一个JdbcTemplate的成员变量,并在dao类的构造方法或通过依赖注入的方式将JdbcTemplate对象注入进来。这样,就可以在dao中使用JdbcTemplate来执行数据库操作了。 通过上述步骤,我们就可以在Spring项目中使用JdbcTemplate来进行数据库操作了。JdbcTemplate提供了一系列的方法,如查询、更新、批处理等,可以根据具体的需求选择合适的方法来使用使用JdbcTemplate可以简化数据库操作的代码,并提高开发效率。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringjdbcTemplate使用](https://blog.csdn.net/ABestRookie/article/details/127232689)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [JdbcTemplate基本使用](https://download.csdn.net/download/weixin_38606076/14939780)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [SpringJdbcTemplate使用](https://blog.csdn.net/qq_38628046/article/details/108111318)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值