JdbcTemplate简介

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

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

  

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

  • execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;

  • update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;

  • query方法及queryForXXX方法:用于执行查询相关语句;

  • call方法:用于执行存储过程、函数相关语句。

下面进行案件分析

在src下面新建一个属性配置文件

1 jdbc.user=root
2 jdbc.password=123456
3 jdbc.driverClass=com.mysql.jdbc.Driver
4 jdbc.jdbcUrl=jdbc\:mysql\:///test

  我们通常将数据库的配置信息单独放到一个文件中,这样也为了方便后期维护

配置Spring配置文件applicationContext.xml

 1 <context:property-placeholder location="classpath:db.properties"/>
2 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
3 <property name="user" value="${jdbc.user}"></property>
4 <property name="password" value="${jdbc.password}"></property>
5 <property name="driverClass" value="${jdbc.driverClass}"></property>
6 <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
7 </bean>
8
9 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
10 <property name="dataSource" ref="dataSource"></property>
11 </bean>

  第一行代码:用来读取db.properties文件中的数据。

  第二行代码:用来配置一个数据源,这里数据实现类来自C3P0中的一个属性类。其中属性的值就是来自于db.properties

  第九行代码:配置一个JdbcTemplate实例,并注入一个dataSource数据源

测试代码

 

1、update()方法

a、通过update插入数据

1 //启动IoC容器
2 ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
3 //获取IoC容器中JdbcTemplate实例
4 JdbcTemplate jdbcTemplate=(JdbcTemplate) ctx.getBean("jdbcTemplate");
5 String sql="insert into user (name,deptid) values (?,?)";
6 int count= jdbcTemplate.update(sql, new Object[]{"caoyc",3});
7 System.out.println(count);

  这里update方法,第二参可以为可变参数。在数据库中可以看到,数据以被正确插入

b、通过update修改数据

1 String sql="update user set name=?,deptid=? where id=?";
2 jdbcTemplate.update(sql,new Object[]{"zhh",5,51});

 c、通过update删除数据

1 String sql="delete from user where id=?";
2 jdbcTemplate.update(sql,51);

2、batchUpdate()批量插入、更新和删除方法

a、批量插入

1 String sql="insert into user (name,deptid) values (?,?)";
2
3 List<Object[]> batchArgs=new ArrayList<Object[]>();
4 batchArgs.add(new Object[]{"caoyc",6});
5 batchArgs.add(new Object[]{"zhh",8});
6 batchArgs.add(new Object[]{"cjx",8});
7
8 jdbcTemplate.batchUpdate(sql, batchArgs);

  batchUpdate方法第二参数是一个元素为Object[]数组类型的List集合

3、从数据中读取数据到实体对象

  先定一个User实体类

 1 package com.proc;
2
3 public class User {
4 private Integer id;
5 private String name;
6 private Integer deptid;
7 public Integer getId() {
8 return id;
9 }
10 public void setId(Integer id) {
11 this.id = id;
12 }
13 public String getName() {
14 return name;
15 }
16 public void setName(String name) {
17 this.name = name;
18 }
19 public Integer getDeptid() {
20 return deptid;
21 }
22 public void setDeptid(Integer deptid) {
23 this.deptid = deptid;
24 }
25
26 public String toString() {
27 return "User [id=" + id + ", name=" + name + ", deptid=" + deptid + "]";
28 }
29 }

a、读取单个对象

1 String sql="select id,name,deptid from user where id=?";
2
3 RowMapper<User> rowMapper=new BeanPropertyRowMapper<User>(User.class);
4 User user= jdbcTemplate.queryForObject(sql, rowMapper,52);
5 System.out.println(user);

  输出结果:

  User [id=52, name=caoyc, deptid=6]

【注意】:1、使用BeanProperytRowMapper要求sql数据查询出来的列和实体属性需要一一对应。如果数据中列明和属性名不一致,在sql语句中需要用as重新取一个别名

     2、使用JdbcTemplate对象不能获取关联对象

b、读取多个对象

1 String sql="select id,name,deptid from user";
2
3 RowMapper<User> rowMapper=new BeanPropertyRowMapper<User>(User.class);
4 List<User> users= jdbcTemplate.query(sql, rowMapper);
5 for (User user : users) {
6 System.out.println(user);
7 }

输出结果

...

User [id=49, name=姓名49, deptid=5]
User [id=50, name=姓名50, deptid=8]
User [id=52, name=caoyc, deptid=6]
User [id=53, name=zhh, deptid=8]
User [id=54, name=cjx, deptid=8]

---

c、获取某个记录某列或者count、avg、sum等函数返回唯一值

1 String sql="select count(*) from user";
2
3 int count= jdbcTemplate.queryForObject(sql, Integer.class);
4 System.out.println(count);

在实际开发中可以怎样用

UserDao.java

 1 package com.proc;
2
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.jdbc.core.BeanPropertyRowMapper;
5 import org.springframework.jdbc.core.JdbcTemplate;
6 import org.springframework.jdbc.core.RowMapper;
7 import org.springframework.stereotype.Repository;
8
9 @Repository
10 public class UserDao {
11
12 @Autowired
13 private JdbcTemplate jdbcTemplate;
14
15 public User get(int id){
16 String sql="select id,name,deptid from user where id=?";
17 RowMapper<User> rowMapper=new BeanPropertyRowMapper<User>(User.class);
18 return jdbcTemplate.queryForObject(sql, rowMapper,id);
19 }
20 }

xml配置:

 1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:aop="http://www.springframework.org/schema/aop"
5 xmlns:context="http://www.springframework.org/schema/context"
6 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
9
10 <context:component-scan base-package="com.proc"></context:component-scan>
11 <context:property-placeholder location="classpath:db.properties"/>
12 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
13 <property name="user" value="${jdbc.user}"></property>
14 <property name="password" value="${jdbc.password}"></property>
15 <property name="driverClass" value="${jdbc.driverClass}"></property>
16 <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
17 </bean>
18
19 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
20 <property name="dataSource" ref="dataSource"></property>
21 </bean>
22 </beans>

代码测试

1 UserDao userDao=(UserDao) ctx.getBean("userDao");
2 System.out.println(userDao.get(53));

原文:

https://www.cnblogs.com/caoyc/p/5630622.html

【转载】Spring JdbcTemplate详解的更多相关文章

  1. [转载]Spring配置文件详解一:

    原文地址:与base-package="com.xx">Spring配置文件详解一:<context:annotation-config/>与<contex ...

  2. Spring JdbcTemplate详解

    为了使 JDBC 更加易于使用,Spring 在 JDBCAPI 上定义了一个抽象层, 以此建立一个JDBC存取框架. 作为 SpringJDBC 框架的核心, JDBC 模板的设计目的是为不同类型的 ...

  3. Spring JdbcTemplate详解(转)

    原文地址:http://www.cnblogs.com/caoyc/p/5630622.html   尊重原创,请访问原文地址 JdbcTemplate简介 Spring对数据库的操作在jdbc上面做 ...

  4. Spring JdbcTemplate详解及项目中的运用

    1.Spring对不同的持久化支持: Spring为各种支持的持久化技术,都提供了简单操作的模板和回调 ORM持久化技术 模板类 JDBC org.springframework.jdbc.core. ...

  5. Spring JdbcTemplate详解(9)

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

  6. Spring AOP详解(转载)所需要的包

    上一篇文章中,<Spring Aop详解(转载)>里的代码都可以运行,只是包比较多,中间缺少了几个相应的包,根据报错,几经百度搜索,终于补全了所有包. 截图如下: 在主测试类里面,有人怀疑 ...

  7. 【转载】Spring AOP详解 、 JDK动态代理、CGLib动态代理

    Spring AOP详解 . JDK动态代理.CGLib动态代理  原文地址:https://www.cnblogs.com/kukudelaomao/p/5897893.html AOP是Aspec ...

  8. Spring RestTemplate详解

    Spring RestTemplate详解   1.什么是REST? REST(RepresentationalState Transfer)是Roy Fielding 提出的一个描述互联系统架构风格 ...

  9. Spring AOP详解及简单应用

    Spring AOP详解   一.前言 在以前的项目中,很少去关注spring aop的具体实现与理论,只是简单了解了一下什么是aop具体怎么用,看到了一篇博文写得还不错,就转载来学习一下,博文地址: ...

随机推荐

  1. 谱聚类算法及其代码(Spectral Clustering)

    https://blog.csdn.net/liu1194397014/article/details/52990015 https://blog.csdn.net/u011089523/articl ...

  2. 项目启动时警告 Establishing SSL connection without server's identity verification is not recommended

    项目启动时控制台提示警告: Tue May 14 23:16:10 CST 2019 WARN: Establishing SSL connection without server's identi ...

  3. Redis For Windows安装及密码

    启动要先开启一个控制台作为服务端,启动服务,然后在重新打开一个控制台,连接服务进行操作. redis-server.exe redis.conf 重新打开一个控制台,刚开始连接服务,因为初始没有密码, ...

  4. c# Invoke的新用法

    在C# 3.0及以后的版本中有了Lamda表达式,像上面这种匿名委托有了更简洁的写法..NET Framework 3.5及以后版本更能用Action封装方法.例如以下写法可以看上去非常简洁: voi ...

  5. Go micro 开发微服务步骤

    1.写 proto文件,定义接口和服务 2.实现 接口,注册 handle 3.调用服务:直接用rpc 客户端调用,或者用 api http web等调用 api http web 等服务可以对客户端 ...

  6. [ kvm ] 学习笔记 5:QEMU-KVM 命令详解

    1. QEMU.KVM .QEMU-KVM QEMU 提供了一系列的硬件模拟设备(cpu.网卡.磁盘等),客户机指令都需要QEMU翻译,因此性能较差.KVM 是Linux 内核提供的虚拟化模块,负责C ...

  7. 使用sql语句创建和删除约束示例代码

    使用sql语句创建和删除约束  约束类型 主键约束(Primary Key constraint) --:要求主键列数据唯一,并且不允许为空.  唯一约束(Unique constraint) --: ...

  8. 【Leetcode_easy】1046. Last Stone Weight

    problem 1046. Last Stone Weight 参考 1. Leetcode_easy_1046. Last Stone Weight; 完

  9. 【Leetcode_easy】908. Smallest Range I

    problem 908. Smallest Range I solution: class Solution { public: int smallestRangeI(vector<int> ...

  10. Keystone

    Kenstone各个概念的比喻: User 住宾馆的人 Credentials 开启房间的钥匙 Authentication 宾馆为了拒绝不必要的人进出宾馆,专门设置的机制,只有拥有钥匙的人才能进出 ...