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 创建一 ...
随机推荐
- 【C#设计模式——创建型模式】抽象工厂模式
抽象工厂模式比工厂模式具有更高层次的抽象性.当要返回一系列相关类中的某一个,而每个类都能根据需要返回不同的对象时,可以选择这种模式.直接进入示例. 示例描述:完成花园的规划,多种花园种类,每个里面多种 ...
- zoj 3785 What day is that day? (打表找规律)
题目 思路:比赛的时候有想过找循环节,但是,打表打错了. 后来,看着过了挺多人,就急了, 看了一下别人的时间 耗时都挺长的,就以为不是找规律, 没想到真是找规律,不过,这个题的数据可能挺大的. AC代 ...
- 最大流 Dinic + Sap 模板
不说别的,直接上模板. Dinic+当前弧优化: struct Edge{ int x,y,c,ne; }e[M*]; int be[N],all; int d[N],q[N]; int stack[ ...
- WEB-INF目录与META-INF目录的作用
/WEB-INF/web.xml Web应用程序配置文件,描述了 servlet 和其他的应用组件配置及命名规则. /WEB-INF/classes/包含了站点所有用的 class 文件,包括 ser ...
- bzoj2561: 最小生成树
如果出现在最小生成树上,那么此时比该边权值小的边无法连通uv.据此跑最小割(最大流)即可. #include<cstdio> #include<cstring> #includ ...
- Samba 4.x.x全版本存在命令执行漏洞
Samba 4.0.0到4.1.10版本的nmbd(the NetBIOS name services daemon)被发现存在远程命令执行漏洞.CVE编号为CVE-2014-3560.目前官方已经发 ...
- javascript数组详解
1.数组的一些方法: <script type="text/javascript"> //var arr = [1,2,3,4]; //性能略高 var arr = n ...
- attachEvent,addEventListener事件绑定
兼容各主流浏览器的事件绑定(在同一个事件上添加多个处理函数). 1.绑定方法: //IE attachEvent(事件名, 函数) oBtn.attachEvent('onclick', aaa); ...
- django - request.raw_post_data 与 request.body
request.raw_post_data 重命名成了 request.body - 在1.3版本之后. 这是当时 起票 的讨论内容:https://code.djangoproject.com/ti ...
- HDU 1387 Team Queue
Team Queue Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total ...