Spring JdbcTemplate

Spring JdbcTemplate

Spring JdbcTemplate基本使用

JdbcTemplate概述

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

JdbcTemplate开发步骤

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

JdbcTemplate快速入门

导坐标

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>

创建accout表和Accout实体

061
package com.kiang.domain;

public class Account {
    private String name;
    private double money;
//省略一堆get set to
}

创建JdbcTemplate对象 & 执行数据库操作

package com.kiang.test;

public class JdbcTemplateTest {
    @Test
    public void test1() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/testjdbc?serverTimezone=UTC");
        dataSource.setUser("root");
        dataSource.setPassword("102576");

        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        int row = jdbcTemplate.update("insert into account values (?,?)","zhangsan",8000);
        System.out.println(row);
    }
}

Tips:

  • .setJdbcUrl() 记得加 ?serverTimezone=UTC 参数
  • 提示无法解析 table 'account' 可以在IDEA里连一下数据库

Spring产生JdbcTemplate对象

我们可以将JdbcTemplate的创建权交给Spring,将数据源DataSource的创建权也交给Spring,在Spring容器内部将数据源DataSource注入到JdbcTemplate模版对象中。

抽取jdbc.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/testjdbc?serverTimezone=UTC
jdbc.username=root
jdbc.password=102576

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

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

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

从容器中获得JdbcTemplate进行添加操作:

@Test
public void test2() throws PropertyVetoException {
    ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
    JdbcTemplate jdbcTemplate = app.getBean(JdbcTemplate.class);

    int row = jdbcTemplate.update("insert into account values (?,?)","lisi",9000);
    System.out.println(row);
}

JdbcTemplate的常用操作

修改操作

package com.kiang.test;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Test
    public void testUpdate() {
        jdbcTemplate.update("update account set money=? where name=?",10000,"lisi");
    }
}

删除和查询全部操作

@Test
public void testDelete() {
    jdbcTemplate.update("delete from account where name=?","lisi");
}
@Test
public void testQueryAll() {
    List<Account> accountList = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
    System.out.println(accountList);
}

查询单个数据操作操作

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

查询计算

@Test
public void testQueryCount() {
    Long aLong = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
    System.out.println(aLong);
}
posted @   AncilunKiang  阅读(50)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示