Spring SimpleJdbcTemplate Querying examples
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的更多相关文章
- Spring JdbcTemplate Querying examples
Here are few examples to show you how to use JdbcTemplate query() methods to query or extract data f ...
- Spring Named Parameters examples in SimpleJdbcTemplate
In JdbcTemplate, SQL parameters are represented by a special placeholder "?" symbol and bi ...
- Spring SimpleJdbcTemplate batchUpdate() example
In this tutorial, we show you how to use batchUpdate() in SimpleJdbcTemplate class. See batchUpdate( ...
- Spring + JdbcTemplate + JdbcDaoSupport examples
In Spring JDBC development, you can use JdbcTemplate and JdbcDaoSupport classes to simplify the over ...
- Spring SimpleJdbcTemplate查询示例
这里有几个例子来说明如何使用SimpleJdbcTemplate query()方法来查询或从数据库中提取数据.在 JdbcTemplate query() 方法,需要手动转换返回的结果转换为一个目标 ...
- Spring AOP Example – Pointcut , Advisor
In last Spring AOP advice examples, the entire methods of a class are intercepted automatically. But ...
- Complete Guide for Spring Boot Actuator
You are here to learn about Spring Boot Actuator for collecting metrics about your production grade ...
- spring boot rest例子
简介: 本文将帮助您使用 Spring Boot 创建简单的 REST 服务. 你将学习 什么是 REST 服务? 如何使用 Spring Initializr 引导创建 Rest 服务应用程序? 如 ...
- 【Spring Boot】构造、访问Restful Webservice与定时任务
Spring Boot Guides Examples(1~3) 参考网址:https://spring.io/guides 创建一个RESTful Web Service 使用Eclipse 创建一 ...
随机推荐
- Android L 使用ART能提高多少性能?
点击打开链接 刚刚结束的 Google I/O 大会上,Android 下一代操作系统「L」带来不少惊喜.新系统运行更快.更省电. 然而开发者对这个新系统也有颇多疑问,比如新的运行模式 ART 对开发 ...
- gulp edm测试
gulp工具的 gulp-mailgun 插件可以将你的html代码,通过mailgun服务器来发送,用于测试,用这个工具发送邮件最适合不过了. 首先我们需要引入gulp和gulp-mailgun模块 ...
- UVa 1025 (动态规划) A Spy in the Metro
题意: 有线性的n个车站,从左到右编号分别为1~n.有M1辆车从第一站开始向右开,有M2辆车从第二站开始向左开.在0时刻主人公从第1站出发,要在T时刻回见车站n 的一个间谍(忽略主人公的换乘时间).输 ...
- [反汇编练习] 160个CrackMe之004
[反汇编练习] 160个CrackMe之004. 本系列文章的目的是从一个没有任何经验的新手的角度(其实就是我自己),一步步尝试将160个CrackMe全部破解,如果可以,通过任何方式写出一个类似于注 ...
- ORACLE 全局索引和本地索引
Oracle数据库中,有两种类型的分区索引,全局索引和本地索引,其中本地索引又可以分为本地前缀索引和本地非前缀索引.下面就分别看看每种类型的索引各自的特点. 全局索引以整个表的数据为对象建立索引,索引 ...
- 《C++ Primer 4th》读书笔记 第3章-标准库类型
原创文章,转载请注明出处:http://www.cnblogs.com/DayByDay/p/3911534.html
- Blog CSS
你好 print("你好.") haode
- Please ensure that adb is correctly located at……问题解决方案
启动android模拟器时.有时会报The connection to adb is down, and a severe error has occured.的错误.在网友说在任务管理器上把所有ad ...
- wifi详解(一)
1 WLAN技术 WLAN是英文WirelessLAN的缩写,就是无线局域网的意思.无线以太网技术是一种基于无线传输的局域网技术,与有线网络技术相比,具有灵活.建网迅速.个人化等特点.将 ...
- oracle 统计语句 与常见函数的归纳(未完待续)
一.统计语句 1. count count(*)与count(0)语句的区别: count(*)统计所有数量 count(0)统计第一列不为空的 2. 两个统计量的减法 select (select ...