Spring JdbcTemplate.queryForObject()

By Arvind Rai, July 25, 2022
Spring JdbcTemplate is the central class in the JDBC core package. It simplifies the use of JDBC with Spring and helps to avoid common errors. On this page we will learn using its queryForObject method.
Find the JdbcTemplate.queryForObject method with different arguments.
1.
<T> T queryForObject(String sql, Class<T> requiredType) throws DataAccessException 
Execute the given SQL and returns the object of required type.
2.
<T> T queryForObject(String sql, Class<T> requiredType, @Nullable Object... args) throws DataAccessException 
Query the given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result object.
3.
<T> T queryForObject(String sql, Object[] args, int[] argTypes, Class<T> requiredType) throws DataAccessException 
Query the given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result object.
4.
<T> T queryForObject(String sql, Object[] args, int[] argTypes, RowMapper<T> rowMapper) throws DataAccessException 
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping a single result row to a result object via a RowMapper.
5.
<T> T queryForObject(String sql, RowMapper<T> rowMapper) throws DataAccessException 
Execute a query given static SQL, mapping a single result row to a result object via a RowMapper.
6.
<T> T queryForObject(String sql, RowMapper<T> rowMapper, @Nullable Object... args) throws DataAccessException 
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping a single result row to a result object via a RowMapper.

Parameters: The sql is the the SQL query to execute.
The requiredType is the type that the result object is expected to match.
The args is the arguments to bind to the query.
The argTypes is the SQL types of the arguments from java.sql.Types.
The rowMapper is a callback that will map one object per row

Returns:
The result object, or null in case of SQL NULL.

Throws:
If there is any problem executing the query, method throws DataAccessException.

Example using Spring Boot

PersonDAO.java
package com.concretepage;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class PersonDAO {
  @Autowired
  private JdbcTemplate jdbcTemplate;

  // queryForObject(String sql, Class<T> requiredType)
  public int getPersonCount() {
	String sql = "select count(*) from person";
	return jdbcTemplate.queryForObject(sql, Integer.class);
  }

  // queryForObject(String sql, Class<T> requiredType, Object... args)
  public String getNameById(int id) {
	String sql = "select name from person where id = ?";
	return jdbcTemplate.queryForObject(sql, String.class, 1);
  }

  // queryForObject(String sql, Object[] args, int[] argTypes, Class<T> requiredType)
  public int getPersonCountByNameAndAge(String name, int age) {
	String sql = "select count(*) from person where name = ? and age = ?";
	Object[] args = { name, age };
	int[] argTypes = { java.sql.Types.CHAR, java.sql.Types.INTEGER };
	return jdbcTemplate.queryForObject(sql, args, argTypes, Integer.class);
  }

  // queryForObject(String sql, Object[] args, int[] argTypes, RowMapper<T> rowMapper)
  public Person getPersonsById(int id) {
	String sql = "select * from person where id = ?";
	Object[] args = { id };
	int[] argTypes = { java.sql.Types.INTEGER };
	return jdbcTemplate.queryForObject(sql, args, argTypes, new RowMapper<Person>() {
	  @Override
	  public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
		Person p = new Person(rs.getString(2), rs.getInt(3));
		p.setId(rs.getInt(1));
		return p;
	  }
	});
  }

  // queryForObject(String sql, RowMapper<T> rowMapper)
  public Person getAdmin() {
	String sql = "select * from person where id = 1";
	return jdbcTemplate.queryForObject(sql, new RowMapper<Person>() {
	  @Override
	  public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
		Person p = new Person(rs.getString(2), rs.getInt(3));
		p.setId(rs.getInt(1));
		return p;
	  }
	});
  }

  // queryForObject(String sql, RowMapper<T> rowMapper, Object... args)
  public int getPersonCount2(String name, int age) {
	String sql = "select count(*) from person where name = ? and age = ?";
	return jdbcTemplate.queryForObject(sql, new RowMapper<Integer>() {
	  @Override
	  public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
		return rs.getInt(1);
	  }
	}, name, age);
  }
} 
Person.java
package com.concretepage;
public class Person {
    private int id;
	private String name;
	private int age;
	public Person(String name, int age) {
	  this.name = name;
	  this.age = age;
	}
	public int getId() {
	  return id;
	}
	public void setId(int id) {
	  this.id = id;
	}
	public String getName() {
	  return name;
	}
	public int getAge() {
	  return age;
	}
} 
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/concretepage
spring.datasource.username=root
spring.datasource.password=cp
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 
pom.xml
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-jdbc</artifactId>
	</dependency>
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>6.0.5</version>
	</dependency>
</dependencies> 
MyApplication.java
package com.concretepage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class MyApplication {
  public static void main(String[] args) {
	ApplicationContext ctx = SpringApplication.run(MyApplication.class, args);
	PersonDAO personDAO = ctx.getBean(PersonDAO.class);
	System.out.println("Total Count: " + personDAO.getPersonCount());
	
	System.out.println(personDAO.getNameById(1));
	
	System.out.println("Count: " + personDAO.getPersonCountByNameAndAge("Mohan", 25));
	
	Person p = personDAO.getPersonsById(1);
	System.out.println(p.getId() + " - " + p.getName() + " - " + p.getAge());
	
	Person admin = personDAO.getAdmin();
	System.out.println(admin.getId() + " - " + admin.getName() + " - " + admin.getAge());	
	
	System.out.println("Count: " + personDAO.getPersonCount2("Mohan", 25));	
  }
} 
Find the MySQL table (person) screenshot used in our demo.
Spring JdbcTemplate.queryForObject()
Find the output.
Total Count: 3
Rakesh
Count: 2
1 - Rakesh - 30
1 - Rakesh - 30
Count: 2 

Reference

Class JdbcTemplate

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us