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. typeof和GetType的区别

    http://stackoverflow.com/questions/4537945/what-is-the-difference-of-getting-type-by-using-gettype-a ...

  2. Mac下安装HBase及详解

    Mac下安装HBase及详解 1. 千篇一律的HBase简介 HBase是Hadoop的数据库, 而Hive数据库的管理工具, HBase具有分布式, 可扩展及面向列存储的特点(基于谷歌BigTabl ...

  3. TCP建立连接和释放的过程,及TCP状态变迁图

    一.TCP报文格式 下面是TCP报文格式图: 重要字段介绍: (1)序号:Seq序号,占32位,用来标识从TCP源端向目的端发送的字节流,发起方发送数据时对此进行标记. (2)确认序号:Ack序号,占 ...

  4. TCSRM 591 div2(1000)(dp)

    挺好的dp 因为有一点限制 必须任意去除一个数 总和就会小于另一个总和 换句话来说就是去除最小的满足 那么就都满足 所以是限制最小值的背包 刚开始从小到大定住最小值来背 TLE了一组数据 后来发现如果 ...

  5. Hibernate映射集合属性

    Hibernate要求持久化集合属性字段必须声明为接口,实际的接口可以是java.util.Set,java.util.Collection,java.util.List,java.util.Map, ...

  6. BZOJ2299: [HAOI2011]向量

    题目:http://www.lydsy.com/JudgeOnline/problem.php?id=2299 题解:乱搞就可以了... 不妨认为有用的只有(a,b)(a,-b)(b,a)(b,-a) ...

  7. Struts框架搭建时所遇到的问题

    问题一:Unable to load configuration. - bean - jar:file:/D:/Tomcat%206.0/webapps/bar/WEB-INF 原       因:可 ...

  8. LeetCode Maximum Product Subarray 最大子序列积

    题意:给一个size大于0的序列,求最大的连续子序列之积.(有正数,负数,0) 思路:正确分析这三种数.0把不同的可能为答案的子序列给隔开了,所以其实可以以0为分隔线将他们拆成多个序列来进行求积,这样 ...

  9. 【C#学习笔记】打开对话框并返回打开文件所在路径

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  10. 【转】Android Studio -修改LogCat的颜色*美爆了*

    原文网址:http://www.2cto.com/kf/201505/400357.html 一. 先看效果 二.设置 File->Settings 或Ctrl + Alt +S 找到 Edit ...