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下HelloWorld项目的R.java文件介绍
R.java文件介绍 HelloWorld工程中的R.java文件 package com.android.hellworld; public final class R { public s ...
- vi 编辑内容中查找字符位置
[root@localhost gdm]# vi /etc/X11/gdm/gdm.conf # You can also use the gdm-restart and gdm-safe-resta ...
- 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 ...
- poj 3101 Astronomy (java 分数的最小公倍数 gcd)
题目链接 要用大数,看了别人的博客,用java写的. 题意:求n个运动周期不完全相同的天体在一条直线上的周期. 分析:两个星球周期为a,b.则相差半周的长度为a*b/(2*abs(a-b)),对于n个 ...
- POJ 2112 - Optimal Milking
原题地址:http://poj.org/problem?id=2112 题目大意:有K个挤奶机(标号为1 ~ K)和C头奶牛(编号为K + 1 ~ K + C),以邻接矩阵的方式给出它们两两之间的距离 ...
- JS闭包的两个使用方向
直接上代码,备用,详见注释 <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="serve ...
- web.xml元素介绍
每一个站的WEB-INF下都有一个web.xml的设定文件,它提供了对我们站台的配置设定.web.xml中定义元素有:◆站台的名称和说明◆针对环境参数(Context)做初始化工作◆Servlet的名 ...
- 【转】零基础写Java知乎爬虫之进阶篇
转自:脚本之家 说到爬虫,使用Java本身自带的URLConnection可以实现一些基本的抓取页面的功能,但是对于一些比较高级的功能,比如重定向的处理,HTML标记的去除,仅仅使用URLConnec ...
- phpDoc 注释案例说明
<?php /** * start page for webaccess * * PHP version 5 * * @category PHP * @package PSI_Web * @au ...
- mysql 基础命令入门学习
登陆到mysql mysql -u 用户名 -p [数据库] 显示数据库 show databases; 使用一个数据库 use 数据库名; 显示表 show tables; 纠正数据 ...