Spring JdbcTemplate增删改查基本用法及封装

    本文介绍Spring JdbcTemplate增删改查基本用法及基于查询的封装:public <T> T queryForObject(String sql, Class<T> tClass, Object... args) ,调用封装后的queryForObject,可以基于sql、返回类型、可选参数值返回Java Bean,Map,或String、int等基本类型。本文涉及:Spring Bean配置,Java 范型使用,JdbcTemplate基本用法。

    环境:mysql5.6,jdk1.8,spring3.2.5。

    一、数据库准备,Mysql5.6

    1、创建数据表jdbc_student,并模拟几个学生数据

CREATE TABLE `jdbc_student` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8
1    lizhuo    34
2    Zara    11
3    Nuha    2
4    Ayan    15
5    AA    12
6    BB    34
7    CC    23
8    DD    32
9    EE    25
2、创建数据表jdbc_student映射类,Student.java
package com.marcus.spring.jdbc;

public class Student {
    private Integer age;
    private String name;
    private Integer id;
	
    @Override  
    public String toString() {  
        return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";  
    } 

    public void setAge(Integer age) {
	this.age = age;
    }

    public Integer getAge() {
	return age;
    }

    public void setName(String name) {
	this.name = name;
    }

    public String getName() {
	return name;
    }

    public void setId(Integer id) {
	this.id = id;
    }

    public Integer getId() {
	return id;
    }
}

二、jdbcTemplate增删改查基本用法

1、查询:返回String、Integer等简单类型,queryForObject(String sql, Class<T> requiredType, Object... args)

public static void main(String[] args) {
	AbstractApplicationContext context = new ClassPathXmlApplicationContext("jdbc.xml");
	JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
	
	String sql = "select name from jdbc_student where id = ?";
	String name = jdbcTemplate.queryForObject(sql, String.class, 1);
	System.out.println("name: " + name);		// name: lizhuo

	sql = "select age from jdbc_student where id = ?";
	int age = jdbcTemplate.queryForObject(sql, Integer.class, 1);
	System.out.println("age: " + age);		// age: 34
	
	context.close();
}
2、查询:返回POJO,Student类,queryForObject(String sql, RowMapper<T> rowMapper, Object... args)
public static void main(String[] args) {
	AbstractApplicationContext context = new ClassPathXmlApplicationContext("jdbc.xml");
	JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
		
	String sql = "select * from jdbc_student where id = ?";
	RowMapper<Student> rowMapper = new BeanPropertyRowMapper<Student>(Student.class);
	Student student = jdbcTemplate.queryForObject(sql, rowMapper, 1);
	System.out.println(student);		// Student [id=1, name=lizhuo, age=34]
		
	context.close();
}

3、查询:返回Map,Map<String, Object> queryForMap(String sql, Object... args)

public static void main(String[] args) {
	AbstractApplicationContext context = new ClassPathXmlApplicationContext("jdbc.xml");
	JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
		
	String sql = "select * from jdbc_student where id = ?";
	Map<String, Object> student = jdbcTemplate.queryForMap(sql, 1);
	System.out.println(student);		// {id=1, name=lizhuo, age=34}
		
	context.close();
}

4、查询:返回List<String>, List<Intege>等,List<T> queryForList(String sql, Class<T> elementType, Object... args)

public static void main(String[] args) {
	AbstractApplicationContext context = new ClassPathXmlApplicationContext("jdbc.xml");
	JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
		
	String sql = "select name from jdbc_student where age between ? and ? ";
	List<String> names = jdbcTemplate.queryForList(sql, String.class, 11, 20);
	System.out.println("names: " + names);		// names: [Zara, Ayan, AA]

	sql = "select age from jdbc_student where age between ? and ? ";
	List<Integer> ages = jdbcTemplate.queryForList(sql, Integer.class, 11, 20);
	System.out.println("ages: " + ages);		// ages: [11, 15, 12]
		
	context.close();
}

5、查询:返回List<Student>, List<T> query(String sql, RowMapper<T> rowMapper, Object... args)

public static void main(String[] args) {
	AbstractApplicationContext context = new ClassPathXmlApplicationContext("jdbc.xml");
	JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
		
	String sql = "select * from jdbc_student where age between ? and ?";
	RowMapper<Student> rowMapper = new BeanPropertyRowMapper<Student>(Student.class);
	List<Student> students = jdbcTemplate.query(sql, rowMapper, 11, 20);
	System.out.println(students);		
        // [Student [id=2, name=Zara, age=11], Student [id=4, name=Ayan, age=15], ]
		
        context.close();
}

6、查询:返回List<Map>, List<Map<String, Object>> queryForList(String sql, Object... args)

public static void main(String[] args) {
	AbstractApplicationContext context = new ClassPathXmlApplicationContext("jdbc.xml");
	JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
		
	String sql = "select * from jdbc_student where age between ? and ?";
	List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, 11,20);
	System.out.println(list);
	// [{id=2, name=Zara, age=11}, {id=4, name=Ayan, age=15}, {id=5, name=AA, age=12}]
		
	context.close();
}

7、增、删、改操作,统一调用 int update(String sql, Object... args)即可

public static void main(String[] args) {
	AbstractApplicationContext context = new ClassPathXmlApplicationContext("jdbc.xml");
	JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
		
	String sql = "insert into jdbc_student (name, age) values (?, ?)";
	jdbcTemplate.update(sql, "name-001", 15);
	queryForStudent(jdbcTemplate);
		
	sql = "update jdbc_student set age = ? where name = ?";
	jdbcTemplate.update(sql, 12, "name-001");
	queryForStudent(jdbcTemplate);
		
	sql = "delete from jdbc_student where name = ?";
	jdbcTemplate.update(sql, "name-001");
	queryForStudent(jdbcTemplate);
		
	context.close();
}
private static void queryForStudent(JdbcTemplate jdbcTemplate) {
	String sql = "select * from jdbc_student where name = ? ";
	RowMapper<Student> rowMapper = new BeanPropertyRowMapper<Student>(Student.class);
	Student student = jdbcTemplate.queryForObject(sql, rowMapper, "name-001");
	System.out.println(student);
}

输出结果如下:

Student [id=10, name=name-001, age=15]
Student [id=10, name=name-001, age=12]
Exception in thread "main" org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
	at org.springframework.dao.support.DataAccessUtils.requiredSingleResult(DataAccessUtils.java:71)
	at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:737)
	at com.marcus.spring.jdbc.JdbcApp.queryForStudent(JdbcApp.java:70)
	at com.marcus.spring.jdbc.JdbcApp.main(JdbcApp.java:42)

8、存储过程调用,参考:JdbcTemplate调用存储过程常见情况及封装

三、基于jdbcTemplate查询的封装

1、BaseJdbcDao.java

package com.marcus.spring.jdbc;

import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SingleColumnRowMapper;

public class BaseJdbcDao {
	private JdbcTemplate jdbcTemplate;
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	@SuppressWarnings("unchecked")
	public <T> List<T> queryForList(String sql, Class<T> tClass, Object... args) {
		RowMapper<T> rowMapper = null;
		if (Map.class.isAssignableFrom(tClass)) {
			rowMapper = (RowMapper<T>) new ColumnMapRowMapper();
		} else if (String.class.equals(tClass) || Integer.class.equals(tClass) 
                            || Long.class.equals(tClass)) {
			rowMapper = new SingleColumnRowMapper<T>(tClass);
		} else {
			rowMapper = new BeanPropertyRowMapper<T>(tClass);
		}
		List<T> list = jdbcTemplate.query(sql, rowMapper, args);
		return list;
	}
	
	public <T> T queryForObject(String sql, Class<T> tClass, Object... args) {
		List<T> list = queryForList(sql, tClass, args);
		return list == null || list.isEmpty() ? null : list.get(0);
	} 
}

2、返回List,List<T> queryForList(String sql, Class<T> tClass, Object... args)

public static void main(String[] args) {
	AbstractApplicationContext context = new ClassPathXmlApplicationContext("jdbc.xml");
	BaseJdbcDao jdbcDao = (BaseJdbcDao) context.getBean("jdbcDao");
		
	//List<String>
	String sql = "select name from jdbc_student where age between ? and ? ";
	List<String> names = jdbcDao.queryForList(sql, String.class, 11, 20);
	System.out.println(names);	//[Zara, Ayan, AA]
		
	//List<Integer>
	sql = "select age from jdbc_student where age between ? and ? ";
	List<Integer> ages = jdbcDao.queryForList(sql, Integer.class, 11, 20);
	System.out.println(ages);	//[11, 15, 12]
		
	//List<Student>
	sql = "select * from jdbc_student where age between ? and ? ";
	List<Student> students = jdbcDao.queryForList(sql, Student.class, 11, 20);
	System.out.println(students);
	//[Student [id=2, name=Zara, age=11], Student [id=4, name=Ayan, age=15], ]
		
	//List<Map>
	sql = "select * from jdbc_student where age between ? and ? ";
	List<Map> maps = jdbcDao.queryForList(sql, Map.class, 11, 20);
	System.out.println(maps);
	//[{id=2, name=Zara, age=11}, {id=4, name=Ayan, age=15}, {id=5, name=AA, age=12}]
		
	context.close();
}

3、返回Object:String, Integer, Student, Map等,<T> T queryForObject(String sql, Class<T> tClass, Object... args)

与jdbcTemplate原生queryForObject最大区别是,查找结果为空返回null,不为空则返回集合第一个元素。

public static void main(String[] args) {
	AbstractApplicationContext context = new ClassPathXmlApplicationContext("jdbc.xml");
	BaseJdbcDao jdbcDao = (BaseJdbcDao) context.getBean("jdbcDao");
		
	//返回 String
	String sql = "select name from jdbc_student where id = ?";
	String name = jdbcDao.queryForObject(sql, String.class, 1);
	System.out.println("id = 1, name = " + name);	//id = 1, name = lizhuo
		
	//返回 Integer
	sql = "select age from jdbc_student where id = ?";
	Integer age = jdbcDao.queryForObject(sql, Integer.class, 1);
	System.out.println("id = 1, age = " + age);	//id = 1, age = 34
		
	//返回 Student
	sql = "select * from jdbc_student where id = ? ";
	Student student = jdbcDao.queryForObject(sql, Student.class, 1);
	System.out.println(student);		//Student [id=1, name=lizhuo, age=34]
		
	//返回 Map
	sql = "select * from jdbc_student where id = ? ";
	Map map = jdbcDao.queryForObject(sql, Map.class, 1);
	System.out.println(map);		//{id=1, name=lizhuo, age=34}
		
	context.close();
}

四、spring配置文件,jdbc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    
   <!-- Initialization for data source -->
   <bean id="dataSource" 
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
      <property name="url" value="jdbc:mysql://47.*.*.*:3306/lmdgh_demo?useUnicode=true&characterEncoding=utf-8"/>
	  <property name="username" value="user" />
	  <property name="password" value="pwd" />
   </bean>

   <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
      <property name="dataSource" ref="dataSource"></property> 
   </bean>
   
   <bean id="jdbcDao" class="com.marcus.spring.jdbc.BaseJdbcDao">  
      <property name="jdbcTemplate" ref="jdbcTemplate"></property>
   </bean>
</beans>

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值