Here are few examples to show how to use SimpleJdbcTemplate query() methods to query or extract data from database. In JdbcTemplate query(), you need to manually cast the returned result to desire object type, and pass an Object array as parameters. In SimpleJdbcTemplate, it is more user friendly and simple.

jdbctemplate vesus simplejdbctemplate

Please compare this SimpleJdbcTemplate example with this JdbcTemplate example.

1. Querying for Single Row

Here’s two ways to show you how to query or extract a single row from database, and convert it into a model class.

1.1 Custom RowMapper

In general, It’s always recommend to implement the RowMapper interface to create a custom RowMapper to suit your needs.

package com.mkyong.customer.model;

import java.sql.ResultSet;
import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class CustomerRowMapper implements RowMapper
{
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Customer customer = new Customer();
customer.setCustId(rs.getInt("CUST_ID"));
customer.setName(rs.getString("NAME"));
customer.setAge(rs.getInt("AGE"));
return customer;
} }
public Customer findByCustomerId(int custId){

	String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = ?";

	Customer customer = getSimpleJdbcTemplate().queryForObject(
sql, new CustomerParameterizedRowMapper(), custId); return customer;
}

1.2 BeanPropertyRowMapper

In SimpleJdbcTemplate, you need to use ‘ParameterizedBeanPropertyRowMapper’ instead of ‘BeanPropertyRowMapper’.

public Customer findByCustomerId2(int custId){

	String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = ?";

	Customer customer = getSimpleJdbcTemplate().queryForObject(sql,
ParameterizedBeanPropertyRowMapper.newInstance(Customer.class), custId); return customer;
}

2. Querying for Multiple Rows

Query or extract multiple rows from database, and convert it into a List.

2.1 ParameterizedBeanPropertyRowMapper

public List<Customer> findAll(){

	String sql = "SELECT * FROM CUSTOMER";

	List<Customer> customers =
getSimpleJdbcTemplate().query(sql,
ParameterizedBeanPropertyRowMapper.newInstance(Customer.class)); return customers;
}

3. Querying for a Single Value

Query or extract a single column value from database.

3.1 Single column name

It shows how to query a single column name as String.

public String findCustomerNameById(int custId){

	String sql = "SELECT NAME FROM CUSTOMER WHERE CUST_ID = ?";

	String name = getSimpleJdbcTemplate().queryForObject(
sql, String.class, custId); return name; }

3.2 Total number of rows

It shows how to query a total number of rows from database.

public int findTotalCustomer(){

	String sql = "SELECT COUNT(*) FROM CUSTOMER";

	int total = getSimpleJdbcTemplate().queryForInt(sql);

	return total;
}
Run it
package com.mkyong.common;

import java.util.ArrayList;
import java.util.List; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mkyong.customer.dao.CustomerDAO;
import com.mkyong.customer.model.Customer; public class SimpleJdbcTemplateApp
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext("Spring-Customer.xml"); CustomerDAO customerSimpleDAO =
(CustomerDAO) context.getBean("customerSimpleDAO"); Customer customerA = customerSimpleDAO.findByCustomerId(1);
System.out.println("Customer A : " + customerA); Customer customerB = customerSimpleDAO.findByCustomerId2(1);
System.out.println("Customer B : " + customerB); List<Customer> customerAs = customerSimpleDAO.findAll();
for(Customer cust: customerAs){
System.out.println("Customer As : " + customerAs);
} List<Customer> customerBs = customerSimpleDAO.findAll2();
for(Customer cust: customerBs){
System.out.println("Customer Bs : " + customerBs);
} String customerName = customerSimpleDAO.findCustomerNameById(1);
System.out.println("Customer Name : " + customerName); int total = customerSimpleDAO.findTotalCustomer();
System.out.println("Total : " + total); }
}

Conclusion

The SimpleJdbcTemplate isn’t a replacement for JdbcTemplate, it’s just a java5-friendly supplement to it.

Spring SimpleJdbcTemplate Querying examples的更多相关文章

  1. Spring JdbcTemplate Querying examples

    Here are few examples to show you how to use JdbcTemplate query() methods to query or extract data f ...

  2. Spring Named Parameters examples in SimpleJdbcTemplate

    In JdbcTemplate, SQL parameters are represented by a special placeholder "?" symbol and bi ...

  3. Spring SimpleJdbcTemplate batchUpdate() example

    In this tutorial, we show you how to use batchUpdate() in SimpleJdbcTemplate class. See batchUpdate( ...

  4. Spring + JdbcTemplate + JdbcDaoSupport examples

    In Spring JDBC development, you can use JdbcTemplate and JdbcDaoSupport classes to simplify the over ...

  5. Spring SimpleJdbcTemplate查询示例

    这里有几个例子来说明如何使用SimpleJdbcTemplate query()方法来查询或从数据库中提取数据.在 JdbcTemplate query() 方法,需要手动转换返回的结果转换为一个目标 ...

  6. Spring AOP Example – Pointcut , Advisor

    In last Spring AOP advice examples, the entire methods of a class are intercepted automatically. But ...

  7. Complete Guide for Spring Boot Actuator

    You are here to learn about Spring Boot Actuator for collecting metrics about your production grade ...

  8. spring boot rest例子

    简介: 本文将帮助您使用 Spring Boot 创建简单的 REST 服务. 你将学习 什么是 REST 服务? 如何使用 Spring Initializr 引导创建 Rest 服务应用程序? 如 ...

  9. 【Spring Boot】构造、访问Restful Webservice与定时任务

    Spring Boot Guides Examples(1~3) 参考网址:https://spring.io/guides 创建一个RESTful Web Service 使用Eclipse 创建一 ...

随机推荐

  1. android的helloworld工程目录学习

    android的helloworld工程目录学习 Android工程的主要目录有src.gen.Android X.X.bin.res等文件夹. 1.     Src文件夹 Src文件夹包含java源 ...

  2. Oracle Create DBLink

    DROP PUBLIC DATABASE LINK ORA11G_DBLINK; CREATE   PUBLIC   DATABASE LINK ORA11G_DBLINKCONNECT TO SYS ...

  3. Android开发之通过反射获取到挂断电话的API

    Android开发黑名单工具类,需要用到挂断电话的API,但是该API处于隐藏状态,需要通过反射得到该方法.. 步骤: 1.通过当前类获取到ServiceManager的字节码 Class< ? ...

  4. struts2中改变struts.xml默认路径

    struts2.X配置文件默认存放路径在/WEB-INF/classes目录下,即将struts.xml放在src的目录下. 但是为了方便管理,开发人员把struts.xml放到其他位置,处理方法如下 ...

  5. BZOJ_1627_[Usaco2007_Dec]_穿越泥地_(bfs)

    描述 http://www.lydsy.com/JudgeOnline/problem.php?id=1627 网格图,给出起点,终点,障碍,求最短路. 分析 简单的宽搜. #include < ...

  6. BZOJ2111: [ZJOI2010]Perm 排列计数

    题目:http://www.lydsy.com/JudgeOnline/problem.php?id=2111 题意:一个1,2,...,N的排列P1,P2...,Pn是Magic的,当且仅当2< ...

  7. asp.net获取当前页面源码并生成静态页面

    StringWriter stringWriter = new StringWriter(); HtmlTextWriter htmlWriter = new HtmlTextWriter(strin ...

  8. SJ9012: IE6 IE7 不支持 JSON 对象

    标准参考 JSON 是一种数据交换格式,RFC 4627 对 JSON 进行了详细描述. 根据 ECMA-262(ECMAScript)第 5 版中描述,JSON 是一个包含了函数 parse 和 s ...

  9. fmri当前相关软件工具整理

    1.spm; 2.afni; 3.fsl; 4.drtools; 5.prtools; 6.phycaa+; 7.cca-fmri;

  10. poj 3160 Father Christmas flymouse

    // 题目描述:从武汉大学ACM集训队退役后,flymouse 做起了志愿者,帮助集训队做一些琐碎的事情,比如打扫集训用的机房等等.当圣诞节来临时,flymouse打扮成圣诞老人给集训队员发放礼物.集 ...