首页 > 其他分享 >Spring JdbcTemplate

Spring JdbcTemplate

时间:2022-10-28 22:14:28浏览次数:46  
标签:account jdbc Spring class JdbcTemplate public 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);
}

标签:account,jdbc,Spring,class,JdbcTemplate,public,jdbcTemplate
From: https://www.cnblogs.com/AncilunKiang/p/16837666.html

相关文章

  • Spring整合Kafaka(二十六)
    1引入依赖<dependency><groupId>org.springframework.kafka</groupId><artifactId>spring-kafka</artifactId></dependency>2配置Kafka配置server、cons......
  • Spring Boot
    SpringBootSpringBoot基础SpringBoot简介SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的初始搭建以及开发过程,简单讲就是牺牲项目的自由......
  • Spring
    SpringSpring简介Spring是什么?Spring是分层的JavaSE/EE应用full-stack轻量级开源框架,以IoC(InverseOfControl:反转控制)和AOP(AspectOrientedProgramming:面向切面编......
  • Spring 注解开发
    使用Spring注解前的配置<?xmlversion="1.0"encoding="UTF8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/20......
  • 16. Spring的基本使用
    一、引入Spring的依赖  通过maven的方式导入jar包,打包方式设置为jar包即可。<!--https://mvnrepository.com/artifact/org.springframework/spring-context-->......
  • springboot启动默认连接数据库问题
    这里是给新手介绍的springboot默认启动是连接数据库的经常很多人蒙蔽,//无数据源启动@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,DataSo......
  • springboot像springnvc那样访问视图
    1.SpringBoot访问静态资源的位置(优先级按以下顺序)classpath默认就是resources,所以classpath:/static/就是resources/static/classpath:/META‐INF/resources/cl......
  • Spring Boot 学习笔记
    SpringBoot简介为什么要使用SpringBoot因为Spring,SpringMVC需要使用的大量的配置文件(xml文件)还需要配置各种对象,把使用的对象放入到spring容器中才能使用对象......
  • 【SpringBoot】引入mybatis及连接Mysql数据库
    创建一个SpringBoot项目其他不赘叙了,引入MyBaties、MySql依赖编辑 创建mysql表CREATETABLEsp_users(`id`INTPRIMARYKEY,`username`VARCHAR(30),`age`INT);刚......
  • jwt+token,springsecurity认证方式总结
    基于redis的认证方式分析redis解决短信验证码时效性,以及使用token的方式判断是否登录的问题。(没用jwt)这里面使用两个拦截器的方式解决:1.给token有效期刷新2.判断用户......