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

1. Querying for Single Row

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

1.1 Custom RowMapper

In general, It’s always recommended 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;
} }

Pass it to queryForObject() method, the returned result will call your custom mapRow() method to match the value into the properly.

public Customer findByCustomerId(int custId){

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

	Customer customer = (Customer)getJdbcTemplate().queryForObject(
sql, new Object[] { custId }, new CustomerRowMapper()); return customer;
}

1.2 BeanPropertyRowMapper

In Spring 2.5, comes with a handy RowMapper implementation called ‘BeanPropertyRowMapper’, which can maps a row’s column value to a property by matching their names. Just make sure both the property and column has the same name, e.g property ‘custId’ will match to column name ‘CUSTID’ or with underscores ‘CUST_ID’.

public Customer findByCustomerId2(int custId){

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

	Customer customer = (Customer)getJdbcTemplate().queryForObject(
sql, new Object[] { custId },
new BeanPropertyRowMapper(Customer.class)); return customer;
}

2. Querying for Multiple Rows

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

2.1 Map it manually

In mutiple return rows, RowMapper is not supported in queryForList() method, you need to map it manually.

public List<Customer> findAll(){

	String sql = "SELECT * FROM CUSTOMER";

	List<Customer> customers = new ArrayList<Customer>();

	List<Map> rows = getJdbcTemplate().queryForList(sql);
for (Map row : rows) {
Customer customer = new Customer();
customer.setCustId((Long)(row.get("CUST_ID")));
customer.setName((String)row.get("NAME"));
customer.setAge((Integer)row.get("AGE"));
customers.add(customer);
} return customers;
}

2.2 BeanPropertyRowMapper

The simplest solution is using the BeanPropertyRowMapper class.

public List<Customer> findAll(){

	String sql = "SELECT * FROM CUSTOMER";

	List<Customer> customers  = getJdbcTemplate().query(sql,
new BeanPropertyRowMapper(Customer.class)); return customers;
}

3. Querying for a Single Value

In this example, it shows how to 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 = (String)getJdbcTemplate().queryForObject(
sql, new Object[] { custId }, String.class); 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 = getJdbcTemplate().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 JdbcTemplateApp
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext("Spring-Customer.xml"); CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO"); Customer customerA = customerDAO.findByCustomerId(1);
System.out.println("Customer A : " + customerA); Customer customerB = customerDAO.findByCustomerId2(1);
System.out.println("Customer B : " + customerB); List<Customer> customerAs = customerDAO.findAll();
for(Customer cust: customerAs){
System.out.println("Customer As : " + customerAs);
} List<Customer> customerBs = customerDAO.findAll2();
for(Customer cust: customerBs){
System.out.println("Customer Bs : " + customerBs);
} String customerName = customerDAO.findCustomerNameById(1);
System.out.println("Customer Name : " + customerName); int total = customerDAO.findTotalCustomer();
System.out.println("Total : " + total); }
}

Conclusion

The JdbcTemplate class, comes with many useful overloaded query methods. It’s advise to refer to the existing query method before you create own customize query method, because Spring may done it for you already.

Spring JdbcTemplate Querying examples的更多相关文章

  1. Spring SimpleJdbcTemplate Querying examples

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

  2. Spring + JdbcTemplate + JdbcDaoSupport examples

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

  3. (转)Spring JdbcTemplate 方法详解

    Spring JdbcTemplate方法详解 文章来源:http://blog.csdn.net/dyllove98/article/details/7772463 JdbcTemplate主要提供 ...

  4. [转]Spring JdbcTemplate 查询分页

    原文:http://blog.csdn.net/xiaofanku/article/details/4280128 现在进行的项目由于数据库的遗留原因(设计的不堪入目)不能用hibernate.所以用 ...

  5. spring jdbcTemplate query

    1. spring jdbcTemplate query需要实现mapRow方法 package com.cdv.apolloagent.jdbc.dao.impl; import java.sql. ...

  6. Spring JdbcTemplate 的使用与学习(转)

    紧接上一篇 (JdbcTemplate是线程安全的,因此可以配置一个简单的JdbcTemplate实例,将这个共享的实例注入到多个DAO类中.辅助的文档) Spring DAO支持 http://ww ...

  7. Spring JdbcTemplate的queryForList(String sql , Class<T> elementType)易错使用--转载

    原文地址: http://blog.csdn.net/will_awoke/article/details/12617383 一直用ORM,今天用JdbcTemplate再次抑郁了一次. 首先看下这个 ...

  8. spring jdbcTemplate源码剖析

    本文浅析 spring jdbcTemplate 源码,主要是学习其设计精髓.模板模式.巧妙的回调 一.jdbcTemplate 类结构 ①.JdbcOperations : 接口定义了方法,如 &l ...

  9. 使用Spring JDBCTemplate简化JDBC的操作

    使用Spring JDBCTemplate简化JDBC的操作 接触过JAVA WEB开发的朋友肯定都知道Hibernate框架,虽然不否定它的强大之处,但个人对它一直无感,总感觉不够灵活,太过臃肿了. ...

随机推荐

  1. json格式的字符串转为json对象遇到特殊字符问题解决

    中午做后台发过来的json的时候转为对象,可是有几条数据一直出不来,检查发现json里包含了换行符,造成这种情况的原因可能是编辑部门在编辑的时候打的回车造成的 假设有这样一段json格式的字符串 va ...

  2. C++STL之整理算法

    这里主要介绍颠倒.旋转.随机排列和分类4中常见的整理算法 1.颠倒(反转) void reverse(_BidIt _First, _BidIt _Last) _OutIt reverse_copy( ...

  3. 面试题_17_to_30_数据类型和 Java 基础面试问题

    17)Java 中应该使用什么数据类型来代表价格?(答案)如果不是特别关心内存和性能的话,使用BigDecimal,否则使用预定义精度的 double 类型. 18)怎么将 byte 转换为 Stri ...

  4. Java 基础之认识 Annotation

    Java 基础之认识 Annotation 从 JDK 1.5 版本开始,Java 语言提供了通用的 Annotation 功能,允许开发者定义和使用自己的 Annotation 类型.Annotat ...

  5. Parallel WebDriver executions using TestNG

    In this post, we will see how does one make use of TestNG to kick off parallel UI tests using WebDri ...

  6. hdu 4825 Xor Sum (建树) 2014年百度之星程序设计大赛 - 资格赛 1003

    题目 题意:给n个数,m次询问,每次给一个数,求这n个数里与这个数 异或 最大的数. 思路:建一个类似字典数的数,把每一个数用 32位的0或者1 表示,查找从高位向底位找,优先找不同的,如果没有不同的 ...

  7. 对于oracle监听器的配置

    oracle 的 net configuration  assist中配置完第一项的监听程序配置(对应文件listener.ora)之后,还要重新配置下第三项本地网络服务名配置(对应文件tnsname ...

  8. Catalan数推导(转载)

    Raney引理: 设整数序列A = {Ai, i=1, 2, …, N},且部分和Sk=A1+…+Ak,序列中所有的数字的和SN=1,在A的N个循环表示中,有且仅有一个序列B,满足B的任意部分和Si均 ...

  9. POJ2796 单调队列

    Feel Good Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 8041   Accepted: 2177 Case Ti ...

  10. Android软件开发需要学什么

    首先,需要学习哪些Android开发技术? Android的开发技术很多,在开始学习的时候不可能一次性全部学会,也没有必要一开始都全部学会,但是有些技术是非常常用的,需要在开始时打好基础,这些技术时: ...