经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
Spring6 的JdbcTemplate的JDBC模板类的详细使用说明 - Rainbow-Sea
来源:cnblogs  作者:Rainbow-Sea  时间:2024/5/13 8:53:34  对本文有异议

1. Spring6 的JdbcTemplate的JDBC模板类的详细使用说明

@


每博一文案

  1. 他伸直双臂,举过头顶,两只手握在一起,伸了个懒腰,望着天地交接的地方,声音飘渺,嗯,有人说高中喜欢的人是能记一辈子的。
  2. 你信吗?
  3. 他侧着头望着他,邢武对他笑,笑得那么云淡风轻,眼神却那么复杂,声音透过风有些不真切地传了过去。
  4. 你这么优秀,不能回在感情上。
  5. 那一瞬间,晴也身上仿佛迸发出耀眼自信的光芒,转过身,逆着光昂起下巴说,一辈子很长,可以做很多事,但我不会把它用来记住一个人。
  6. 我晴也不可能毁在任何事情上。
  7. 信我,我不是懦夫。
  8. 如果我敢拿未来赌一把,你会让我输吗?
  9. 晴也把选择权重新拾了起来,郑重地交还到邢武手中。
  10. 他知道邢武的担忧和闪躲,也知道他的顾虑和徘徊。
  11. 无论是他的家庭,他的出身,他的背景,让他不敢去想以后。
  12. 所以晴也把自己的决心赤裸裸地洒在这片戈壁滩上,让他清晰地感受着,神情凝重地望着邢武,身影被夕阳拉得颀长,那一刻,他只感觉到一股强大的力量撞进他的心脏。
  13. 仿佛藏着排山倒海的光束向他奔腾而来,那么强烈,那么坚定。
  14. 他的生命中从来没有出现过这样一个人,一个不惧天地万物,不怕世俗捆绑的女孩儿,一个浑身是光让他看见未来的女孩儿。
  15. 一个充满智慧,勇敢,把命运牢牢攥在手中的女孩儿。
  16. 他忽然很怕眼前的这个女孩儿,怕过了这辈子就再也遇不到了。
  17. 如果他都敢赌,他又有什么理由退缩呢?
  18. ——————《耀眼》

JdbcTemplate 是Spring 提供的一个JDBC模板类,是对JDBC的封装,简化JDBC代码,当然,你也可以不用,可以让Spring集成其它的ORM框架,例如:MyBatis,Hibernate 等。其中JDBC关于数据库的连接也是一个重要的内容,想要了解更多的大家可以移步至:?????? JDBC_ChinaRainbowSea的博客-CSDN博客

下面我们正式开始对 JdbcTemplate 上的学习,完成增删改查。

2. 环境准备

这里,我们新建一个模块,方便学习,如下:因为我们这里是Spring6,而Spring6最低支持的JDK是17,所以我这里是 JDK17的。

在这里插入图片描述
新建好模块以后,我们需要导入相关的依赖,这里我们通过 maven 导入依赖。关于Maven 的内容呢,大家可以移步至:??????Maven_ChinaRainbowSea的博客-CSDN博客 ,进行更多的学习了解

具体的依赖有:

  1. spring context 依赖 (spring6 的依赖)
  2. mysql-connector-java(关于MySQL驱动的依赖,因为我们要连接数据库,这里我们连接的是MySQL数据库)
  3. spring-jdbc (spring jdbc,这个依赖中有JdbcTemplate)
  4. junit (Junit4 单元测试依赖)

特殊的还有这个,也得添加上

在这里插入图片描述

  1. <repositories>
  2. <repository>
  3. <id>repository.spring.milestone</id>
  4. <name>Spring Milestone Repository</name>
  5. <url>https://repo.spring.io/milestone</url>
  6. </repository>
  7. </repositories>

在这里插入图片描述

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.rainbowsea</groupId>
  7. <artifactId>spring6-009-jdbc-blog</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <properties>
  10. <maven.compiler.source>17</maven.compiler.source>
  11. <maven.compiler.target>17</maven.compiler.target>
  12. </properties>
  13. <repositories>
  14. <repository>
  15. <id>repository.spring.milestone</id>
  16. <name>Spring Milestone Repository</name>
  17. <url>https://repo.spring.io/milestone</url>
  18. </repository>
  19. </repositories>
  20. <dependencies>
  21. <!-- spring context 依赖-->
  22. <dependency>
  23. <groupId>org.springframework</groupId>
  24. <artifactId>spring-context</artifactId>
  25. <version>6.0.11</version>
  26. </dependency>
  27. <!-- mysql驱动 -->
  28. <dependency>
  29. <groupId>mysql</groupId>
  30. <artifactId>mysql-connector-java</artifactId>
  31. <version>8.0.30</version>
  32. </dependency>
  33. <!--spring jdbc,这个依赖中有JdbcTemplate-->
  34. <dependency>
  35. <groupId>org.springframework</groupId>
  36. <artifactId>spring-jdbc</artifactId>
  37. <version>6.0.0-M2</version>
  38. </dependency>
  39. <!-- junit4 -->
  40. <dependency>
  41. <groupId>junit</groupId>
  42. <artifactId>junit</artifactId>
  43. <version>4.13.2</version>
  44. <scope>test</scope>
  45. </dependency>
  46. </dependencies>
  47. </project>

3. 数据准备

首先,我们创建一个名为 spring6的数据库,想要了解SQL语句的内容的,大家可以移步至?????? SQL语法学习_ChinaRainbowSea的博客-CSDN博客

  1. /* 判断该数据库是否存在,不存在,创建*/
  2. CREATE DATABASE IF NOT EXISTS spring6;

然后在 spring6 数据库中创建一个名为 user 的数据表

  1. CREATE TABLE `user` (
  2. `id` int NOT NULL AUTO_INCREMENT,
  3. `real_name` varchar(255) ,
  4. `age` int ,
  5. PRIMARY KEY (`id`) USING BTREE
  6. ) ;
  7. -- ----------------------------
  8. -- Records of user
  9. -- ----------------------------
  10. INSERT INTO `user` VALUES (1, '李四', 33);
  11. INSERT INTO `user` VALUES (2, '李华', 20);
  12. INSERT INTO `user` VALUES (3, '李华', 21);

在这里插入图片描述
在这里插入图片描述

准备实体类:表user对应的实体类User。根据user 数据表结构创建对于的Bean 实体类。

注意: 这里我们定义用对应简单类型的包装类,来定义成员变量,防止数据库的数值为Null时,报错,中断。

在这里插入图片描述

  1. package com.rainbowsea.spring6.bean;
  2. /**
  3. * user 数据表对应的映射的 bean 对象
  4. */
  5. public class User {
  6. // 定义包装类,作为属性类型,防止 数据库中的数值为 null,报错
  7. private Integer id;
  8. private String realName;
  9. private Integer age;
  10. public User(Integer id, String realName, Integer age) {
  11. this.id = id;
  12. this.realName = realName;
  13. this.age = age;
  14. }
  15. public User() {
  16. }
  17. public Integer getId() {
  18. return id;
  19. }
  20. public void setId(Integer id) {
  21. this.id = id;
  22. }
  23. public String getRealName() {
  24. return realName;
  25. }
  26. public void setRealName(String realName) {
  27. this.realName = realName;
  28. }
  29. public Integer getAge() {
  30. return age;
  31. }
  32. public void setAge(Integer age) {
  33. this.age = age;
  34. }
  35. @Override
  36. public String toString() {
  37. return "User{" +
  38. "id=" + id +
  39. ", realName='" + realName + '\'' +
  40. ", age=" + age +
  41. '}';
  42. }
  43. }

配置编写相关的spring.xml的信息

JdbcTemplate 是Spring 提供好的类,这类的完整类名是:org.springframework.jdbc.core.JdbcTemplate 。这个类上的使用,我们 new 对象就好了,而Spring 可以帮我们 new 对象,所以,我们就将这个new JdbcTemplate 对象这件事交给 Spring 来做。直接将这个类配置到 spring.xml 的配置文件当中,纳入 Bean管理即可。

在这里插入图片描述

我们来看一下这个JdbcTemplate源码:

在这里插入图片描述
所以这里,我们只需要配置好 DataSource 数据源,用来连接数据库即可,将DataSource 属性进行 set 注入赋值上。可以看到JdbcTemplate中有一个DataSource属性,这个属性是数据源,我们都知道连接数据库需要Connection对象,而生成Connection对象是数据源负责的。所以我们需要给JdbcTemplate设置数据源属性。
所有的数据源都是要实现javax.sql.DataSource接口的。这个数据源可以自己写一个,也可以用写好的,比如:阿里巴巴的德鲁伊连接池,c3p0,dbcp等。我们这里自己先手写一个数据源。

自己的数据源,数据源存在的目的是为了提供 Connection 对象;只要实现了DataSource 接口的都是数据源:德鲁伊连接池,C3p0连接池,dbcp连接池,都实现了DataSource 接口

如下:

在这里插入图片描述
重写其中的**public Connection getConnection() throws SQLException ** 方法,注意是没有参数的。

在这里插入图片描述

  1. @Override
  2. public Connection getConnection() throws SQLException {
  3. try {
  4. // 注册驱动
  5. Class<?> clazz = Class.forName(driver);
  6. // 获取数据库连接对象
  7. Connection connection = DriverManager.getConnection(url, userName, password);
  8. System.out.println(connection);
  9. return connection;
  10. } catch (Exception e) {
  11. e.printStackTrace();
  12. }
  13. return null;
  14. }
  1. package com.rainbowsea.spring6.bean;
  2. import javax.sql.DataSource;
  3. import java.io.PrintWriter;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.SQLException;
  7. import java.sql.SQLFeatureNotSupportedException;
  8. import java.util.logging.Logger;
  9. /**
  10. * 自己的数据源,数据源存在的目的是为了提供 Connection 对象
  11. * 只要实现了DataSource 接口的都是数据源
  12. * 德鲁伊连接池,C3p0连接池,dbcp连接池,都实现了DataSource 接口
  13. */
  14. public class MyDataSource implements DataSource {
  15. private String driver;
  16. private String url;
  17. private String userName;
  18. private String password;
  19. public MyDataSource() {
  20. }
  21. public MyDataSource(String driver, String url, String userName, String password) {
  22. this.driver = driver;
  23. this.url = url;
  24. this.userName = userName;
  25. this.password = password;
  26. }
  27. public String getDriver() {
  28. return driver;
  29. }
  30. public void setDriver(String driver) {
  31. this.driver = driver;
  32. }
  33. public String getUrl() {
  34. return url;
  35. }
  36. public void setUrl(String url) {
  37. this.url = url;
  38. }
  39. public String getUserName() {
  40. return userName;
  41. }
  42. public void setUserName(String userName) {
  43. this.userName = userName;
  44. }
  45. public String getPassword() {
  46. return password;
  47. }
  48. public void setPassword(String password) {
  49. this.password = password;
  50. }
  51. @Override
  52. public String toString() {
  53. return "MyDataSource{" +
  54. "driver='" + driver + '\'' +
  55. ", url='" + url + '\'' +
  56. ", userName='" + userName + '\'' +
  57. ", password='" + password + '\'' +
  58. '}';
  59. }
  60. @Override
  61. public Connection getConnection() throws SQLException {
  62. try {
  63. // 注册驱动
  64. Class<?> clazz = Class.forName(driver);
  65. // 获取数据库连接对象
  66. Connection connection = DriverManager.getConnection(url, userName, password);
  67. System.out.println(connection);
  68. return connection;
  69. } catch (Exception e) {
  70. e.printStackTrace();
  71. }
  72. return null;
  73. }
  74. @Override
  75. public Connection getConnection(String username, String password) throws SQLException {
  76. return null;
  77. }
  78. @Override
  79. public PrintWriter getLogWriter() throws SQLException {
  80. return null;
  81. }
  82. @Override
  83. public void setLogWriter(PrintWriter out) throws SQLException {
  84. }
  85. @Override
  86. public void setLoginTimeout(int seconds) throws SQLException {
  87. }
  88. @Override
  89. public int getLoginTimeout() throws SQLException {
  90. return 0;
  91. }
  92. @Override
  93. public Logger getParentLogger() throws SQLFeatureNotSupportedException {
  94. return null;
  95. }
  96. @Override
  97. public <T> T unwrap(Class<T> iface) throws SQLException {
  98. return null;
  99. }
  100. @Override
  101. public boolean isWrapperFor(Class<?> iface) throws SQLException {
  102. return false;
  103. }
  104. }

写完数据源,我们需要把这个数据源传递给JdbcTemplate。因为JdbcTemplate中有一个DataSource属性;同时获取为该 DataSource 数据源,通过Spring的set 注入,为其中的成员变量赋值。就是连接我们MySQL数据库的一些信息。如下:

在这里插入图片描述

  1. <!-- 配置自己写的数据源-->
  2. <!-- 当然,也可以集成其他人或者其他组织开发的数据源,例如:c3p0,dbcp druid-->
  3. <bean id="dataSource" class="com.rainbowsea.spring6.bean.MyDataSource">
  4. <property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
  5. <property name="url" value="jdbc:mysql://localhost:3306/spring6"></property>
  6. <property name="userName" value="root"></property>
  7. <property name="password" value="123"></property>
  8. </bean>

这时候,我们就可以将这个数据源传递给JdbcTemplate。因为JdbcTemplate中有一个DataSource属性。在这里插入图片描述

在这里插入图片描述

  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. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <!-- 配置自己写的数据源-->
  6. <!-- 当然,也可以集成其他人或者其他组织开发的数据源,例如:c3p0,dbcp druid-->
  7. <bean id="dataSource" class="com.rainbowsea.spring6.bean.MyDataSource">
  8. <property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
  9. <property name="url" value="jdbc:mysql://localhost:3306/spring6"></property>
  10. <property name="userName" value="root"></property>
  11. <property name="password" value="123"></property>
  12. </bean>
  13. <!-- 配置JdbcTemplate -->
  14. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  15. <property name="dataSource" ref="dataSource"></property>
  16. </bean>
  17. </beans>

这里,我们的环境准备好了,数据表也准备好了,下面就可以开始通过Spring 的JdbcTemplate 操作数据库了(对数据库进行增删改查)的操作了。具体内容如下。

4. 开始

4.1 从数据表中插入(添加)数据

首先,我们通过 Spring 读取上面我们配置好的spinrg.xml 文件当中的,从而实例化 JdbcTemplate 类对象。

在这里插入图片描述
然后使用:jdbcTemplate.update() 的方法,执行SQL语句。

需要注意的是:在Spring当中的JdbcTemplate,对于数据库上的增删改,执行SQL语句都是使用update() 的方法处理的。

  1. 第一个参数:String sql

  2. 第二个参数: @Nullable Object... args 是一个可变参数(是一个数组),表示

    表示:SQL语句当中的? 占位符的要填入的值。

在这里插入图片描述

返回值:int 表示修改/更新的记录条数。

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  1. package com.rainbowsea.test;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. import org.springframework.jdbc.core.JdbcTemplate;
  6. public class JdbcTest {
  7. @Test
  8. public void testInsert() {
  9. // 获取JdbcTemplate对象
  10. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
  11. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
  12. // 执行插入操作
  13. // 注意:insert delete update的sql语句,都是执行update方法。,? 表示占位符
  14. // 因为 id 是自增的,所以,这里我们不赋值
  15. String sql = "insert into user(real_name,age) values(?,?)";
  16. // 返回修改的记录条数
  17. int count = jdbcTemplate.update(sql, "张三", 30);
  18. System.out.println("插入的记录条数:" + count);
  19. }
  20. }

在这里插入图片描述

4.2 从数据表中修改数据

在Spring当中的JdbcTemplate,对于数据库上的增删,执行SQL语句都是使用update() 的方法处理的。

我们这里:将id 为1的,real_name修改为:张小六,age 为 18

在这里插入图片描述

  1. package com.rainbowsea.test;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. import org.springframework.jdbc.core.JdbcTemplate;
  6. public class JdbcTest {
  7. @Test
  8. public void testUpdate() {
  9. // 获取JdbcTemplate对象
  10. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
  11. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
  12. // 执行插入操作
  13. // 注意:insert delete update的sql语句,都是执行update方法。,? 表示占位符
  14. // 执行更新操作
  15. String sql = "update user2 set real_name = ?, age = ? where id = ?";
  16. int count = jdbcTemplate.update(sql, "张小六", 18, 1);
  17. System.out.println(count);
  18. }
  19. }

在这里插入图片描述

4.3 从数据表中删除数据

在Spring当中的JdbcTemplate,对于数据库上的增改,执行SQL语句都是使用update() 的方法处理的。

我们这里:将id 为4的一条记录删除了。

在这里插入图片描述

  1. package com.rainbowsea.test;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. import org.springframework.jdbc.core.JdbcTemplate;
  6. public class JdbcTest {
  7. @Test
  8. public void testDelete() {
  9. // 获取JdbcTemplate对象
  10. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
  11. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
  12. // 执行插入操作
  13. // 编写SQL语句,? 表示占位符
  14. String sql = "delete from user2 where id = ?";
  15. // 执行更新操作
  16. // 注意:insert delete update的sql语句,都是执行update方法。
  17. // 返回修改的记录条数
  18. int count = jdbcTemplate.update(sql, 4);
  19. System.out.println("插入的记录条数:" + count);
  20. }
  21. }

在这里插入图片描述

4.4 从数据表中查询一个对象

关于查询一条记录,使用 jdbcTemplate.queryForObject() 方法:

在这里插入图片描述

  1. 第一个参数:String sql 要执行的SQL语句

  2. 第二个参数:BeanPropertyRowMapper 与对应数据库表中 bean 类的相映射的类。一般用: new BeanPropertyRowMapper<>(T.class) 这样的对象装配上。Bean属性值和数据库记录行的映射对象。在构造方法中指定映射的对象类型。

    在这里插入图片描述
    在这里插入图片描述

  1. 第三个参数:SQL语句当中的 占位符。可变长参数,给sql语句的占位符问号传值。

  2. 返回值:运用了泛型,也就是对应数据库表中在Java当中相对应,映射的 bean 类。

在这里插入图片描述
这里我们查询一个id为1的,其中的ID,real_name,age 的一条记录

在这里插入图片描述

  1. import com.rainbowsea.spring6.bean.User;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  6. import org.springframework.jdbc.core.JdbcTemplate;
  7. public class JdbcTest {
  8. @Test
  9. public void testSelectOne() {
  10. // 获取JdbcTemplate对象
  11. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
  12. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
  13. // 执行插入操作
  14. // 编写SQL语句,? 表示占位符
  15. String sql = "select id, real_name, age from user2 where id = ?";
  16. // 执行更新操作
  17. // 返回对应查询到的 Bean 类
  18. User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), 1);
  19. System.out.println(user);
  20. }
  21. }

在这里插入图片描述

4.5 从数据表中查询一个值

查询数据表当中有几条记录,对应查询数据表中的一个值的内容,我们同样还是使用:jdbcTemplate.queryForObject() 方法来进行。不同的是,这个参数是两个的,是对应的类对象,

  1. 比如这里我们查询的是一个数据表中有几条记录,几条记录,就是一个值了,一个数值类型的类对象了,可以是 int.class,也可以是 long.class,还可以是 short.class 因为只要是数值类型就可以了。
  2. 返回值是对应类的包装类,

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

  1. import com.rainbowsea.spring6.bean.User;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  6. import org.springframework.jdbc.core.JdbcTemplate;
  7. import java.util.List;
  8. public class JdbcTest {
  9. /**
  10. * 查询数据表中的一个值
  11. */
  12. @Test
  13. public void testSelectOneValue() {
  14. // 获取JdbcTemplate对象
  15. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
  16. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
  17. // 执行插入操作
  18. // 编写SQL语句,? 表示占位符
  19. // 执行select
  20. String sql = "select count(1) from user2";
  21. // 返回对应数据类型的包装类
  22. Integer count = jdbcTemplate.queryForObject(sql, int.class);
  23. System.out.println(count);
  24. }
  25. }

在这里插入图片描述
用 Long.class 也是可以的。

在这里插入图片描述

4.6 从数据表中查询多条记录

查询数据表中的多个对象,我们就要使用:jdbcTemplate.query() 方法了

  1. 第一个参数:同样还是:要执行的SQL语句
  2. 第二个参数:。Bean属性值和数据库记录行的映射对象。在构造方法中指定映射的对象类型。;BeanPropertyRowMapper 与对应数据库表中 bean 类的相映射的类。一般用: new BeanPropertyRowMapper<>(T.class) 这样的对象装配上。
  3. 返回值:是一个List 集合了,因为我们查询到的多条记录,自然就是存储到集合当中去了。

在这里插入图片描述
这里我们查询,user2 表中的所有用户的所有信息。

在这里插入图片描述

  1. import com.rainbowsea.spring6.bean.User;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  6. import org.springframework.jdbc.core.JdbcTemplate;
  7. import java.util.List;
  8. public class JdbcTest {
  9. /**
  10. * 查询多条记录
  11. */
  12. @Test
  13. public void testSelectAll() {
  14. // 获取JdbcTemplate对象
  15. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
  16. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
  17. // 执行插入操作
  18. // 编写SQL语句,? 表示占位符
  19. // 执行select
  20. String sql = "select id, real_name, age from user2";
  21. List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
  22. System.out.println(users);
  23. }
  24. }

在这里插入图片描述

4.7 从数据表中批量添加数据

对于数据表中的批量添加数据,我们这里需要用上:jdbcTemplate.batchUpdate() 方法

  1. 第一个参数:String sql 要执行的SQL语句

  2. 第二个参数: List<Object[]> batchArgs 是一个List集合当中存储 Object[ ] 数组,注意是数组,这个List 就是,我们批量插入数据时,对于SQL语句当中的 ? 占位符的传值,因为这个参数是: List<Object[]> batchArgs,所以我们需要将我们 ?占位符的值,放入到List 集合当中,再作为参数,传给jdbcTemplate.batchUpdate() 方法。

    在这里插入图片描述

  1. 返回值:就是你各个批量插入的记录的,各个成功的记录条数,比如这里我们批量添加了3条记录,那么如果三条记录都插入成功了的话,就是[1,1,1]。表示每执行一次这个:"insert into user2(real_name,age) values(?,?)"; SQL语句就会影响到一条记录。

插入这条记录,产生了一条记录的影响。

三条记录,各自都是只产生了一条记录的影响

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  1. import com.rainbowsea.spring6.bean.User;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  6. import org.springframework.jdbc.core.JdbcTemplate;
  7. import java.util.ArrayList;
  8. import java.util.Arrays;
  9. import java.util.List;
  10. public class JdbcTest {
  11. /**
  12. * 批量添加数据
  13. */
  14. @Test
  15. public void testAddBatch() {
  16. // 获取JdbcTemplate对象
  17. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
  18. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
  19. // 批量添加,id 是自增的,这里可以省略
  20. String sql = "insert into user2(real_name,age) values(?,?)";
  21. Object[] objs1 = {"小花", 20};
  22. Object[] objs2 = {"小明", 21};
  23. Object[] objs3 = {"小刚", 22};
  24. // 将要修改的数据封装到 List 集合当中,再作为参数传入
  25. List<Object[]> list = new ArrayList<>();
  26. list.add(objs1);
  27. list.add(objs2);
  28. list.add(objs3);
  29. int[] count = jdbcTemplate.batchUpdate(sql, list);
  30. System.out.println(Arrays.toString(count));
  31. }
  32. }

在这里插入图片描述

4.8 从数据表中批量修改数据

从数据表中批量修改数据还是使用:jdbcTemplate.batchUpdate() 方法。唯一不同的就是执行的SQL语句不同而已。下面我们将id 为 5,6,7 的 age 改为 10,11,12

在这里插入图片描述

在这里插入图片描述

  1. import com.rainbowsea.spring6.bean.User;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  6. import org.springframework.jdbc.core.JdbcTemplate;
  7. import java.util.ArrayList;
  8. import java.util.Arrays;
  9. import java.util.List;
  10. public class JdbcTest {
  11. /**
  12. * 批量修改
  13. */
  14. @Test
  15. public void testUpdateBatch() {
  16. // 获取JdbcTemplate对象
  17. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
  18. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
  19. // 批量修改
  20. String sql = "update user2 set age = ? where id = ?";
  21. Object[] objs1 = { 10, 5};
  22. Object[] objs2 = { 11, 6};
  23. Object[] objs3 = { 12, 7};
  24. // 将要修改的数据封装到 List 集合当中,再作为参数传入
  25. List<Object[]> list = new ArrayList<>();
  26. list.add(objs1);
  27. list.add(objs2);
  28. list.add(objs3);
  29. int[] count = jdbcTemplate.batchUpdate(sql, list);
  30. System.out.println(Arrays.toString(count));
  31. }
  32. }

在这里插入图片描述

4.9 从数据表中批量删除数据

从数据表中批量删除数据还是使用:jdbcTemplate.batchUpdate() 方法。唯一不同的就是执行的SQL语句不同而已。下面我们将user 数据表中的 id 为 5,6,7 的记录删除了。

在这里插入图片描述

  1. import com.rainbowsea.spring6.bean.User;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  6. import org.springframework.jdbc.core.JdbcTemplate;
  7. import java.util.ArrayList;
  8. import java.util.Arrays;
  9. import java.util.List;
  10. public class JdbcTest {
  11. /**
  12. * 批量删除
  13. */
  14. @Test
  15. public void testDeleteBatch() {
  16. // 获取JdbcTemplate对象
  17. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
  18. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
  19. // 批量删除
  20. String sql = "delete from user2 where id = ?";
  21. Object[] objs1 = {5};
  22. Object[] objs2 = {6};
  23. Object[] objs3 = {7};
  24. // 将要修改的数据封装到 List 集合当中,再作为参数传入
  25. List<Object[]> list = new ArrayList<>();
  26. list.add(objs1);
  27. list.add(objs2);
  28. list.add(objs3);
  29. int[] count = jdbcTemplate.batchUpdate(sql, list);
  30. System.out.println(Arrays.toString(count));
  31. }
  32. }

在这里插入图片描述

4.10 JdbcTemplate 使用回调函数

使用回调函数,可以参与的更加细节:例如:如果你想写JDBC代码,可以使用callback回调函数

想要执行回调函数,用使用上 jdbcTemplate.execute() 方法,

在这里插入图片描述

  1. 第一个参数是:String sql 要执行的SQL语句
  2. 第二个参数是:PreparedStatementCallback action ,是个接口,我们要传其实例化对象,

在这里插入图片描述
PreparedStatementCallback,一般我们通常是使用 lambda 表达式 ,简化代码。

在这里插入图片描述
在这里插入图片描述
需要注意的是:注册回调函数,当execute 方法执行的时候,回调函数中的doInPreparedStatement()会被调用

  1. 返回值:就是这里运用的泛型,返回值,就是你传的 T.class 的 Bean 对象。

这里我们使用回调函数,查询 user 数据表中 id 为 2的 用户的,id, real_name,age 的记录信息

在这里插入图片描述

  1. import com.rainbowsea.spring6.bean.User;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. import org.springframework.dao.DataAccessException;
  6. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  7. import org.springframework.jdbc.core.JdbcTemplate;
  8. import org.springframework.jdbc.core.PreparedStatementCallback;
  9. import java.sql.PreparedStatement;
  10. import java.sql.ResultSet;
  11. import java.sql.SQLException;
  12. import java.util.ArrayList;
  13. import java.util.Arrays;
  14. import java.util.List;
  15. public class JdbcTest {
  16. /**
  17. * 回调函数
  18. * 如果你想写JDBC代码,可以使用callback回调函数
  19. */
  20. @Test
  21. public void testCallback() {
  22. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
  23. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
  24. // 准备 sql语句
  25. String sql = "select id,real_name,age from user2 where id = ?";
  26. // 注册回调函数,当execute 方法执行的时候,回调函数中的doInPreparedStatement()会被调用
  27. User user = jdbcTemplate.execute(sql, new PreparedStatementCallback<User>() {
  28. @Override
  29. public User doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
  30. User user = null;
  31. // 1 表示第一个占位符,?的下标, 为 2
  32. ps.setInt(1,2);
  33. ResultSet resultSet = ps.executeQuery();
  34. if(resultSet.next()) {
  35. int id = resultSet.getInt("id");
  36. String realName = resultSet.getString("real_name");
  37. int age = resultSet.getInt("age");
  38. user = new User(id,realName,age);
  39. }
  40. return user;
  41. }
  42. });
  43. System.out.println(user);
  44. }
  45. }

在这里插入图片描述

4.11 JdbcTemplate 配合使用上德鲁伊连接池

上面演示的是用我们自己写的数据源。这里我们其实也是可以使用别人写好的。例如比较牛的德鲁伊连接池。
第一步:引入德鲁伊连接池的依赖。(毕竟是别人写的,我需要导入,才能使用),使用 maven 导入。

在这里插入图片描述

  1. <!--引入德鲁伊连接池-->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>druid</artifactId>
  5. <version>1.1.8</version>
  6. </dependency>

第二步:将德鲁伊中的数据源配置到 spring.xml 配置文件中。和配置我们自己写的一样。就是一些:对应数据库的注册驱动,指明数据库的所在位置,以及连接数据库的账号和密码。

需要特别注意的是:注意这里是:driverClassName,是简单类型进行set注入对属性赋值,简单类型可以用 value

在这里插入图片描述
在这里插入图片描述

而如果是使用:driver,用 ref了

在这里插入图片描述
在这里插入图片描述

这里我们用:driverClassName,进行简单类型的set 注入,对 this.driver 成员变量的属性赋值。

在这里插入图片描述

  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. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <!-- 引入德鲁伊连接池-->
  6. <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
  7. <!-- 注意这里是:driverClassName,,如果是 driver 是 非简单类型了,是Driver 类型-->
  8. <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
  9. <property name="url" value="jdbc:mysql://localhost:3306/spring6"></property>
  10. <property name="username" value="root"></property>
  11. <property name="password" value="123"></property>
  12. </bean>
  13. <!-- 配置JdbcTemplate -->
  14. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  15. <property name="dataSource" ref="druidDataSource"></property>
  16. </bean>
  17. </beans>

下面,我们测试,使用德鲁伊数据库连接池,进行对数据库的查询:

查询id 为1的一条记录。

在这里插入图片描述
在这里插入图片描述
查询成功。

我们再使用德鲁伊进行多个数据的查询。同样也是没有问题的。

在这里插入图片描述

5. 总结:

  1. JdbcTemplate 是Spring 提供的一个JDBC模板类,是对JDBC的封装,简化JDBC代码,当然,你也可以不用,可以让Spring集成其它的ORM框架,例如:MyBatis,Hibernate 等。

  2. 使用JdbcTemplate 需要导入的如下 jar依赖

    1. 1. spring context 依赖 (spring6 的依赖)
    2. 2. mysql-connector-java(关于MySQL驱动的依赖,因为我们要连接数据库,这里我们连接的是MySQL数据库)
    3. 3. spring-jdbc (spring jdbc,这个依赖中有JdbcTemplate)
    4. 4. junit (Junit4 单元测试依赖)
  3. 在Spring当中的JdbcTemplate,对于数据库上的增删改,执行SQL语句都是使用update() 的方法处理的。

  4. 关于查询一条记录,使用 jdbcTemplate.queryForObject() 方法:

  5. 查询数据表中的多个对象,我们就要使用:jdbcTemplate.query() 方法了

  6. 查询数据表当中有几条记录,对应查询数据表中的一个值的内容,我们同样还是使用:jdbcTemplate.queryForObject() 方法来进行。不同的是,这个参数是两个的,是对应的类对象。需要注意的第二个参数,使用的是:对应返回类型的 T.class 类

  7. 使用回调函数,可以参与的更加细节:例如:如果你想写JDBC代码,可以使用callback回调函数

    想要执行回调函数,用使用上 jdbcTemplate.execute() 方法, 需要注意的是:注册回调函数,当execute 方法执行的时候,回调函数中的doInPreparedStatement()会被调用

  8. 对于数据表中的批量添加删除修改数据,我们这里需要用上:jdbcTemplate.batchUpdate() 方法

6. 最后:

“在这个最后的篇章中,我要表达我对每一位读者的感激之情。你们的关注和回复是我创作的动力源泉,我从你们身上吸取了无尽的灵感与勇气。我会将你们的鼓励留在心底,继续在其他的领域奋斗。感谢你们,我们总会在某个时刻再次相遇。”

在这里插入图片描述

原文链接:https://www.cnblogs.com/TheMagicalRainbowSea/p/18188270

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号