Spring JdbcTemplate Querying examples
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的更多相关文章
- Spring SimpleJdbcTemplate Querying examples
Here are few examples to show how to use SimpleJdbcTemplate query() methods to query or extract data ...
- Spring + JdbcTemplate + JdbcDaoSupport examples
In Spring JDBC development, you can use JdbcTemplate and JdbcDaoSupport classes to simplify the over ...
- (转)Spring JdbcTemplate 方法详解
Spring JdbcTemplate方法详解 文章来源:http://blog.csdn.net/dyllove98/article/details/7772463 JdbcTemplate主要提供 ...
- [转]Spring JdbcTemplate 查询分页
原文:http://blog.csdn.net/xiaofanku/article/details/4280128 现在进行的项目由于数据库的遗留原因(设计的不堪入目)不能用hibernate.所以用 ...
- spring jdbcTemplate query
1. spring jdbcTemplate query需要实现mapRow方法 package com.cdv.apolloagent.jdbc.dao.impl; import java.sql. ...
- Spring JdbcTemplate 的使用与学习(转)
紧接上一篇 (JdbcTemplate是线程安全的,因此可以配置一个简单的JdbcTemplate实例,将这个共享的实例注入到多个DAO类中.辅助的文档) Spring DAO支持 http://ww ...
- Spring JdbcTemplate的queryForList(String sql , Class<T> elementType)易错使用--转载
原文地址: http://blog.csdn.net/will_awoke/article/details/12617383 一直用ORM,今天用JdbcTemplate再次抑郁了一次. 首先看下这个 ...
- spring jdbcTemplate源码剖析
本文浅析 spring jdbcTemplate 源码,主要是学习其设计精髓.模板模式.巧妙的回调 一.jdbcTemplate 类结构 ①.JdbcOperations : 接口定义了方法,如 &l ...
- 使用Spring JDBCTemplate简化JDBC的操作
使用Spring JDBCTemplate简化JDBC的操作 接触过JAVA WEB开发的朋友肯定都知道Hibernate框架,虽然不否定它的强大之处,但个人对它一直无感,总感觉不够灵活,太过臃肿了. ...
随机推荐
- C#获取本机IP以及无线网ip
1 private void GetIP() 2 { 3 string hostName = Dns.GetHostName();//本机名 4 //System.Net.IPAddress ...
- hibernate中的SessionFactory,Session分别表示什么啊?如何理解?
Session接口 Session接口对于Hibernate 开发人员来说是一个最重要的接口.然而在Hibernate中,实例化的Session是一个轻量级的类,创建和销毁它都不会 ...
- iOS学习笔记: 使用CAShapeLayer创建带有空心区域的遮罩层
CAShapeLayer是用来接受矢量Path,直接使用GPU来进行渲染的特殊图层.看下面效果: 对应代码: let markLayer = CAShapeLayer(); markLayer.fra ...
- 函数fil_node_create
/*******************************************************************//** Appends a new file to the c ...
- UVa 580 (递推) Critical Mass
题意: 有两种盒子分别装有铀(U)和铅(L),现在把n个盒子排成一列(两种盒子均足够多),而且要求至少有3个铀放在一起,问有多少种排放方法. 分析: n个盒子排成一列,共有2n中方案,设其中符合要求的 ...
- hdu2457:DNA repair
AC自动机+dp.问改变多少个字符能让目标串不含病毒串.即走过多少步不经过病毒串终点.又是同样的问题. #include<cstdio> #include<cstring> # ...
- C#计算程序执行速度
long t1 = DateTime.Now.Ticks; //执行程序,例如处理100个文件 long t2 = DateTime.Now.Ticks; Response.Write("执 ...
- IIS Server is too busy 解决方法(IIS6)
Server is too busy意思是服务器繁忙,资源不够用 为什么会出现这个问题呢? 因为服务器的配置不同,所能承受的压力不同. 而服务器默认对链接数,线程数等有设置,但这个设置太小,基本不够用 ...
- phpDoc 注释案例说明
<?php /** * start page for webaccess * * PHP version 5 * * @category PHP * @package PSI_Web * @au ...
- temp - Linux administration handbook 答案
我开始做第一章后的练习题,发觉不是很容易随意地回答,就像是C++ primer之后的练习题的感觉. 自己有这么多不会的,让我感觉很不爽啊- -! 先不要要求自己一下子都明了,一口吃不成胖子,先找一份工 ...