飞道的博客

Spring JdbcTemplate.queryForObject()

272人阅读  评论(0)

Spring JdbcTemplate 是JDBC核心包中的中心类。它简化了 JDBC 与 Spring 的使用,并有助于避免常见错误。在此页面上,我们将学习使用queryForObject 方法。
JdbcTemplate.queryForObject不同参数的方法。
1. 

<T> T queryForObject(String sql, Class<T> requiredType) throws DataAccessException 

执行给定的 SQL 并返回所需类型的对象。
2.

<T> T queryForObject(String sql, Class<T> requiredType, @Nullable Object... args) throws DataAccessException 

查询给定的 SQL 以从 SQL 创建预准备语句和要绑定到查询的参数列表,需要一个结果对象。
3.

<T> T queryForObject(String sql, Object[] args, int[] argTypes, Class<T> requiredType) throws DataAccessException 

查询给定的 SQL 以从 SQL 创建预准备语句和要绑定到查询的参数列表,需要一个结果对象。
4.

<T> T queryForObject(String sql, Object[] args, int[] argTypes, RowMapper<T> rowMapper) throws DataAccessException 

查询给定的 SQL,用于从 SQL 创建预准备语句和要绑定到查询的参数列表,通过 RowMapper将单个结果行映射到结果对象

5.

<T> T queryForObject(String sql, RowMapper<T> rowMapper) throws DataAccessException 

执行给定静态 SQL 的查询,通过RowMapper将单个结果行映射到结果对象

6.

<T> T queryForObject(String sql, RowMapper<T> rowMapper, @Nullable Object... args) throws DataAccessException 

查询给定 SQL 以从 SQL 创建预准备语句和要绑定到查询的参数列表,通过RowMapper将单个结果行映射到结果对象

参数:

sql是要执行的 SQL 查询。
requiredType 是结果对象应匹配的类型。
args 是要绑定到查询的参数
argType是参数的 SQL 类型java.sql.Types。
rowMapper是一个回调,它将每行映射一个对象

返回:
结果对象,如果是 SQL NULL,则为 null。

抛出:
如果执行查询时遇到任何问题,则抛出DataAccessException。
 

使用Spring Boot的示例

PersonDAO.java


   
  1. package com.concretepage;
  2. import java.sql.ResultSet;
  3. import java.sql.SQLException;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.jdbc.core.JdbcTemplate;
  6. import org.springframework.jdbc.core.RowMapper;
  7. import org.springframework.stereotype.Repository;
  8. @Repository
  9. public class PersonDAO {
  10. @Autowired
  11. private JdbcTemplate jdbcTemplate;
  12. // queryForObject(String sql, Class&lt;T&gt; requiredType)
  13. public int getPersonCount() {
  14. String sql = "select count(*) from person";
  15. return jdbcTemplate.queryForObject(sql, Integer.class);
  16. }
  17. // queryForObject(String sql, Class&lt;T&gt; requiredType, Object... args)
  18. public String getNameById(int id) {
  19. String sql = "select name from person where id = ?";
  20. return jdbcTemplate.queryForObject(sql, String.class, 1);
  21. }
  22. // queryForObject(String sql, Object[] args, int[] argTypes, Class&lt;T&gt; requiredType)
  23. public int getPersonCountByNameAndAge(String name, int age) {
  24. String sql = "select count(*) from person where name = ? and age = ?";
  25. Object[] args = {name, age};
  26. int[] argTypes = {java.sql.Types.CHAR, java.sql.Types.INTEGER};
  27. return jdbcTemplate.queryForObject(sql, args, argTypes, Integer.class);
  28. }
  29. // queryForObject(String sql, Object[] args, int[] argTypes, RowMapper&lt;T&gt; rowMapper)
  30. public Person getPersonsById(int id) {
  31. String sql = "select * from person where id = ?";
  32. Object[] args = {id};
  33. int[] argTypes = {java.sql.Types.INTEGER};
  34. return jdbcTemplate.queryForObject(sql, args, argTypes, new RowMapper<Person>() {
  35. @Override
  36. public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
  37. Person p = new Person(rs.getString(2), rs.getInt(3));
  38. p.setId(rs.getInt(1));
  39. return p;
  40. }
  41. });
  42. }
  43. // queryForObject(String sql, RowMapper&lt;T&gt; rowMapper)
  44. public Person getAdmin() {
  45. String sql = "select * from person where id = 1";
  46. return jdbcTemplate.queryForObject(sql, new RowMapper<Person>() {
  47. @Override
  48. public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
  49. Person p = new Person(rs.getString(2), rs.getInt(3));
  50. p.setId(rs.getInt(1));
  51. return p;
  52. }
  53. });
  54. }
  55. // queryForObject(String sql, RowMapper&lt;T&gt; rowMapper, Object... args)
  56. public int getPersonCount2(String name, int age) {
  57. String sql = "select count(*) from person where name = ? and age = ?";
  58. return jdbcTemplate.queryForObject(sql, new RowMapper<Integer>() {
  59. @Override
  60. public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
  61. return rs.getInt(1);
  62. }
  63. }, name, age);
  64. }
  65. }

Person.java


   
  1. package com.concretepage;
  2. public class Person {
  3. private int id;
  4. private String name;
  5. private int age;
  6. public Person(String name, int age) {
  7. this.name = name;
  8. this.age = age;
  9. }
  10. public int getId() {
  11. return id;
  12. }
  13. public void setId(int id) {
  14. this.id = id;
  15. }
  16. public String getName() {
  17. return name;
  18. }
  19. public int getAge() {
  20. return age;
  21. }
  22. }

application.properties


   
  1. spring.datasource.url=jdbc:mysql://localhost:3306/concretepage?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
  2. spring.datasource.username=root
  3. spring.datasource.password=root
  4. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

pom.xml


   
  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/maven-v4_0_0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.concretepage</groupId>
  7. <artifactId>soap-ws</artifactId>
  8. <version>0.0.1-SNAPSHOT</version>
  9. <packaging>jar</packaging>
  10. <name>spring-demo</name>
  11. <description>Spring Demo Application</description>
  12. <parent>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-parent</artifactId>
  15. <version>2.7.4</version>
  16. <relativePath />
  17. </parent>
  18. <properties>
  19. <java.version>16</java.version>
  20. </properties>
  21. <dependencies>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-jdbc</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>mysql</groupId>
  32. <artifactId>mysql-connector-java</artifactId>
  33. <version>8.0.30</version>
  34. </dependency>
  35. </dependencies>
  36. <build>
  37. <plugins>
  38. <plugin>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-maven-plugin</artifactId>
  41. </plugin>
  42. </plugins>
  43. </build>
  44. </project>

MyApplication.java


   
  1. package com.concretepage;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.context.ApplicationContext;
  5. @SpringBootApplication
  6. public class MyApplication {
  7. public static void main(String[] args) {
  8. ApplicationContext ctx = SpringApplication.run(MyApplication.class, args);
  9. PersonDAO personDAO = ctx.getBean(PersonDAO.class);
  10. System.out.println("Total Count: " + personDAO.getPersonCount());
  11. System.out.println(personDAO.getNameById(1));
  12. System.out.println("Count: " + personDAO.getPersonCountByNameAndAge("Mohan", 25));
  13. Person p = personDAO.getPersonsById(1);
  14. System.out.println(p.getId() + " - " + p.getName() + " - " + p.getAge());
  15. Person admin = personDAO.getAdmin();
  16. System.out.println(admin.getId() + " - " + admin.getName() + " - " + admin.getAge());
  17. System.out.println("Count: " + personDAO.getPersonCount2("Mohan", 25));
  18. }
  19. }

查找我们的演示中使用的 MySQL 表(人)屏幕截图。

输出。


   
  1. Total Count: 3
  2. Rakesh
  3. Count: 2
  4. 1 - Rakesh - 30
  5. 1 - Rakesh - 30
  6. Count: 2

参考

类 Jdbc 模板

下载源代码

spring-jdbctemplate-queryforobject.zip

 


转载:https://blog.csdn.net/allway2/article/details/127604005
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场