JdbcTemplate常用方法解析

news2024/9/20 5:31:09

文章目录

  • 1.JdbcTemplate简介
  • 2.JdbcTemplate主要方法:
  • 3.常用方法介绍
    • update()方法增删改
    • query()查询方法

1.JdbcTemplate简介

JdbcTemplate是Spring JDBC的核心类,借助该类提供的方法可以很方便的实现数据的增删改查。

Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中。

JdbcTemplate位于 spring-jdbc-4.3.0.RELEASE.jar 中。其全限定命名为org.springframework.jdbc.core.JdbcTemplate。要使用JdbcTemlate还需一个 spring-tx-4.3.0.RELEASE.jar 这个包包含了事务和异常控制

2.JdbcTemplate主要方法:

JdbcTemplate主要提供以下五类方法:

  • execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
  • update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;
  • query方法及queryForXXX方法:用于执行查询相关语句;
  • call方法:用于执行存储过程、函数相关语句。

xml中的配置:

<!-- 扫描 -->
<context:component-scan base-package="com.xxx.*"></context:component-scan>

<!-- 不属于自己工程的对象用bean来配置 -->
<!-- 配置数据库连接池 -->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close" p:username="root" p:password="123456">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/test"></property>
</bean>

<!-- 配置jdbcTemplate -->
<bean class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="dataSource"></bean>

3.常用方法介绍

数据库user_info表:
在这里插入图片描述
先创建一个实体对象,对应数据库表中的信息,方便之后的查询操作

package com.xxx.vo;

public class UserInfo {

    private int id;
    private String userName;
    private String password;

    public int getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "UserInfo [id=" + id + ", userName=" + userName + ", password=" + password + "]";
    }
    
}

update()方法增删改

修改(包含增、删、改):update()方法,另有批量插入方法batchUpdate()

UserInfoDao.java代码:

@Repository
public class UserInfoDao {

    @Autowired
        //从容器中自动扫描获取jdbcTemplate
    private JdbcTemplate jdbcTemplate;

        //update()实现增加数据
    public boolean insert(int id,String userName,String password){
        String sql = "insert into user_info values (?,?,?)";
        return jdbcTemplate.update(sql,id,userName,password)>0;
    }
    
    //update()实现修改
    public boolean update(int id,String userName,String password){
        String sql = "update user_info set user_name=?,password=? where id=?";
        return jdbcTemplate.update(sql,userName,password,id)>0;
    } 
    
    //update()实现删除
    public boolean delete(int id){
        String sql = "delete from user_info where id=?";
        return jdbcTemplate.update(sql,id)>0;
    }

}

测试类代码:

public class Test {

    public static void main(String[] args) {
        
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
        UserInfoDao userDao = applicationContext.getBean(UserInfoDao.class);
        
        boolean insert = userDao.insert(1,"Jim", "123");
        boolean update = userDao.update(1,"Tom","123456");
        boolean delete = userDao.delete(1);
     System.out.println("插入:"+insert+",修改:"+update+",删除:"+delete);
        }
}

测试结果:在这里插入图片描述

query()查询方法

查询:查询单个值、查询一个对象、查询多个对象

查询单个值

//查询单个值
public boolean login(String userName,String password){
    try {
        String sql = "select id from user_info where user_name=? and password=?";
        jdbcTemplate.queryForObject(sql,String.class,userName,password);
        return true;
    } catch (DataAccessException e) {
        return false;
    }
}

查询一个对象:RowMapper方法和ResultSetExtractor方法

//查询单个对象
public UserInfo getById(int id){
    String sql = "select id,user_name,password from user_info where id=?";
    
    //RowMapper方法
    class UserInfoRowMapper implements RowMapper<UserInfo>{

        @Override
        public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(rs.getInt("id"));
            userInfo.setUserName(rs.getString("user_name"));
            userInfo.setPassword(rs.getString("password"));
            return userInfo;
        }
        
    }
    
    return jdbcTemplate.queryForObject(sql,new UserInfoRowMapper(),id);

    //RowMapper方法的Lambda表达式
    return jdbcTemplate.queryForObject(sql,(ResultSet rs,int rowNum)->{
        UserInfo userInfo = new UserInfo();
        userInfo.setId(rs.getInt("id"));
        userInfo.setUserName(rs.getString("user_name"));
        userInfo.setPassword(rs.getString("password"));
        return userInfo;
    },id);
    
    //ResultSetExtractor方法
    class UserInfoResultSet implements ResultSetExtractor<UserInfo>{

        @Override
        public UserInfo extractData(ResultSet rs) throws SQLException, DataAccessException {
            UserInfo userInfo = null;
            if(rs.next()){
                userInfo = new UserInfo();
                userInfo.setId(rs.getInt("id"));
                userInfo.setUserName(rs.getString("user_name"));
                userInfo.setPassword(rs.getString("password"));
            }
            return userInfo;
        }
    }
    return jdbcTemplate.query(sql,new UserInfoResultSet(),id);
    
    //ResultSetExtractor方法的lambda表达式
    return jdbcTemplate.query(sql,(ResultSet rs)->{
        UserInfo userInfo = null;
        if(rs.next()){
            userInfo = new UserInfo();
            userInfo.setId(rs.getInt("id"));
            userInfo.setUserName(rs.getString("user_name"));
            userInfo.setPassword(rs.getString("password"));
        }
        return userInfo;
    },id);
    
}

查询多个对象:RowMapper方法和ResultSetExtractor方法

//查询多个对象
public List<UserInfo> selectAll(){
    String sql = "select id,user_name,password from user_info";
    
    //RowMapper方法
    class UserInfoRowMapper implements RowMapper<UserInfo>{
        
        @Override
        public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(rs.getInt("id"));
            userInfo.setUserName(rs.getString("user_name"));
            userInfo.setPassword(rs.getString("password"));
            return userInfo;
        }
        
    }
    return jdbcTemplate.query(sql,new UserInfoRowMapper());
    
    
    //RowMapper方法的Lambda表达式
    return jdbcTemplate.query(sql,(ResultSet rs,int rowNum)->{
        UserInfo userInfo = new UserInfo();
        userInfo.setId(rs.getInt("id"));
        userInfo.setUserName(rs.getString("user_name"));
        userInfo.setPassword(rs.getString("password"));
        return userInfo;
    });
    
    //ResultSetExtractor方法
    class UserInfoResultSet implements ResultSetExtractor<List<UserInfo>>{

        @Override
        public List<UserInfo> extractData(ResultSet rs) throws SQLException, DataAccessException {
            List<UserInfo> list = new ArrayList<>();
            while(rs.next()){
                UserInfo userInfo = new UserInfo();
                userInfo.setId(rs.getInt("id"));
                userInfo.setUserName(rs.getString("user_name"));
                userInfo.setPassword(rs.getString("password"));
                list.add(userInfo);
            }
            return list;
        }
        
    }
    return jdbcTemplate.query(sql, new UserInfoResultSet());
    
    //ResultSetExtractor方法的lambda表达式
    return jdbcTemplate.query(sql,(ResultSet rs)->{
        List<UserInfo> list = new ArrayList<>();
        while(rs.next()){
            UserInfo userInfo = new UserInfo();
            userInfo.setId(rs.getInt("id"));
            userInfo.setUserName(rs.getString("user_name"));
            userInfo.setPassword(rs.getString("password"));
            list.add(userInfo);
        }
        return list;
    });
    
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/358938.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

小波神经网络(WNN)的实现(Python,附源码及数据集)

文章目录一、理论基础1、小波神经网络结构2、前向传播过程3、反向传播过程4、建模步骤二、小波神经网络的实现1、训练过程&#xff08;WNN.py&#xff09;2、测试过程&#xff08;test.py&#xff09;3、测试结果4、参考源码及实验数据集一、理论基础 小波神经网络&#xff08…

Python实现性能自动化测试,还可以如此简单

Python实现性能自动化测试&#xff0c;还可以如此简单 目录&#xff1a;导读 一、思考❓❔ 二、基础操作&#x1f528;&#x1f528; 三、综合案例演练&#x1f528;&#x1f528; 四、总结&#x1f4a1;&#x1f4a1; 写在最后 一、思考❓❔ 1.什么是性能自动化测试? 性…

宁盾上榜第五版《CCSIP 2022 中国网络安全行业全景册》

2月1日&#xff0c;国内网络安全行业媒体Freebuf咨询正式发布《CCSIP&#xff08;China Cyber Security Panorama&#xff09;2022 中国网络安全行业全景册》第五版。宁盾作为国产身份安全厂商入驻身份识别和访问管理&#xff08;SSO、OTP、IDaaS&#xff09;及边界访问控制&am…

Unity毛发系统TressFX Exporter

Unity 数字人交流群&#xff1a;296041238 一&#xff1a;在Maya下的TressFX Exporter 插件安装步骤&#xff1a; 1. 下载Maya的TressFX Exporter插件 下载地址&#xff1a;TressFX Exporter 链接&#xff1a;https://github.com/Unity-China/cn.unity.hairfx.core/tree/m…

货仓选址 AcWing(JAVA)

在一条数轴上有 N家商店&#xff0c;它们的坐标分别为 A1∼AN。 现在需要在数轴上建立一家货仓&#xff0c;每天清晨&#xff0c;从货仓到每家商店都要运送商品。 为了提高效率&#xff0c;求把货仓建在何处&#xff0c;可以使得货仓到每家商店的距离之和最小。 输入格式&#…

Spring Cloud Alibaba--ActiveMQ微服务详解之消息队列(四)

上篇讲述高并发情况下的数据库处理方式&#xff1a;分布式事务管理机制。即使我们做到这一步并发情况只能稍微得到缓解&#xff0c;当然千万级别的问题不大&#xff0c;但在面对双十一淘宝这类的达上亿的并发的时候仅仅靠分布式事务管理还是远远不够&#xff0c;即使数据库可以…

基于Django和vue的微博用户情感分析系统

完整代码&#xff1a;https://download.csdn.net/download/weixin_55771290/87471350概述这里简单说明一下项目下下来直接跑起的方法。前提先搞好python环境和vue环境,保证你有一个账户密码连上数据库mysql。1、pip install requirements.txt 安装python包2、修改mysql数据库的…

Hadoop HDFS的主要架构与读写文件

一、Hadoop HDFS的架构 HDFS&#xff1a;Hadoop Distributed File System&#xff0c;分布式文件系统 &#xff11;&#xff0c;NameNode 存储文件的metadata&#xff0c;运行时所有数据都保存到内存&#xff0c;整个HDFS可存储的文件数受限于NameNode的内存大小一个Block在…

使用物联网进行智能能源管理的10大优势

如今&#xff0c;物联网推动了许多行业的自动化流程和运营效率&#xff0c;而物联网在能源领域的应用尤其受到消费者、企业甚至政府的关注。除了对电力供应链的诸多好处之外&#xff0c;物联网能源管理系统还让位于新的智能电网&#xff0c;并有望实现更高的安全性和效率。基于…

软件架构知识6-高性能数据库集群:读写分离

一、读写分离 读写分离原理&#xff1a;将数据库读写操作分散到不同的节点上&#xff1a; 读写分离的基本实现是&#xff1a; 1、数据库服务器搭建主从集群&#xff0c;一主一从&#xff0c;一主多从都可以&#xff1b; 2、数据库主机负责读写操作&#xff0c;从机只负责读操…

【2023-02-20】JS逆向之翼支付

提示&#xff1a;文章仅供参考&#xff0c;禁止用于非法途径 文章目录前言分析总结前言 真的好久没更了…… 提示&#xff1a;以下是本篇文章正文内容&#xff0c;下面案例可供参考 分析 进到网页&#xff0c;加载两个接口 applyLoginFactor 接口返回一个RSA公钥&#xff0…

vulnhub zico2

总结&#xff1a;脏牛提权 目录 下载地址 漏洞分析 信息收集 木马上传 反弹shell 提权 下载地址 zico2.ova (Size: 828 MB)Download: https://www.dropbox.com/s/dhidaehguuhyv9a/zico2.ovaDownload (Mirror): https://download.vulnhub.com/zico/zico2.ova使用方法&…

机智的Open3D学习生活(第一集):入坑前的准备工作

1、Open3D的开源项目地址&#xff1a; https://github.com/isl-org/Open3D 2、Open3D的官网地址&#xff1a; http://www.open3d.org/ 3、Open3D的文档地址&#xff1a;http://www.open3d.org/docs/latest/tutorial/visualization/cpu_rendering.html 后续我将以此文档作为蓝…

如何单独清除某个网页的缓存(reload)

有时候在自己服务器上调试的时候&#xff0c;刷新一直不更新&#xff0c;样式改了也看不到&#xff0c;就很烦 今天教你一个方法快速清除 F12 控制台情况下右击左上角的刷新 这三个分别代表&#xff1a; ①正常重新加载(Ctrl R): 正常重新加载 此方法,浏览器发送请求时会…

深入Spring底层透析Bean创建过程之拨云见日篇

目录前言一.BeanFactory快速入门1. BeanFactory创建Bean2. BeanFactory和ApplicationContext的关系3. 和ApplicationContext区别(高频问点)4. BeanFactory的继承体系5. ApplicationContext的继承体系二.Bean实例化的基本流程&#xff08;重点)前言 首先感谢您的阅览&#xff0…

Git复习

1. 引言 现在要用到Git&#xff0c;复习一下关于Git的指令&#xff0c;知识摘自《Pro Git》 2. 起步 git和其他版本控制软件最大的差别在于git是直接记录某个版本的快照&#xff0c;而不是逐渐地比较差异。 安装: sudo apt install git-all设置用户信息&#xff1a; git c…

上海亚商投顾:沪指放量大涨 券商等权重板块全线飙升

上海亚商投顾前言&#xff1a;无惧大盘涨跌&#xff0c;解密龙虎榜资金&#xff0c;跟踪一线游资和机构资金动向&#xff0c;识别短期热点和强势个股。市场情绪三大指数今日集体反弹&#xff0c;沪指、深成指单边拉升&#xff0c;午后均涨超2%&#xff0c;上证50大涨超2.7%&…

加入CSDN的一年,我收获了这些……

加入CSDN的一年&#xff0c;我收获了这些……加入CSDN的一年&#xff0c;我收获了这些……加入CSDN的一年&#xff0c;我收获了这些…… &#x1f680;&#x1f680;时光如白驹过隙般&#xff0c;飞逝而过。一转眼&#xff0c;我就已经是一名大二的学生了&#xff0c;也已经在…

LeetCode 每日一题2347. 最好的扑克手牌

Halo&#xff0c;这里是Ppeua。平时主要更新C语言&#xff0c;C&#xff0c;数据结构算法......感兴趣就关注我吧&#xff01;你定不会失望。 &#x1f308;个人主页&#xff1a;主页链接 &#x1f308;算法专栏&#xff1a;专栏链接 我会一直往里填充内容哒&#xff01; &…

Homekit智能家居一智能灯泡

一、什么是智能灯 传统的灯泡是通过手动打开和关闭开关来工作。有时&#xff0c;它们可以通过声控、触控、红外等方式进行控制&#xff0c;或者带有调光开关&#xff0c;让用户调暗或调亮灯光。 智能灯泡内置有芯片和通信模块&#xff0c;可与手机、家庭智能助手、或其他智能…