Spring框架|JdbcTemplate的增删改查操作


一、XML配置

关于XML配置中逐条代码的含义,可以参照Spring框架集成JdbcTemplate,这里不做赘述。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop.xsd ">
	<!-- 配置连接池对象 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybase2" />
		<property name="user" value="root"/>
		<property name="password" value="Hudie"/>
	</bean>
	<!-- 配置JdbcTemplate模板对象 -->	
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<!-- dao -->
	<bean id="userDao" class="com.gql.dao.UserDaoImp">
		<property name="jdbcTemplate" ref="jdbcTemplate"></property>
	</bean>
	
	<!-- service -->
	<bean id="userService" class="com.gql.service.UserServiceImp">
		<property name="userDao" ref="userDao"></property>
	</bean>
</beans>

二、数据库user表

  • 创建一个简单的User用户表,有三个属性,分别是int类型的id,String类型的name,int类型的age。
  • 由于这里使用的age是int类型的,也为后面在dao层中封装查询[n,m]条记录的类型转换int–>Infeger–>Object买下了伏笔。
create database mybase2;
USE mybase2;
CREATE TABLE `user` (
	`id` INT(10) NOT NULL AUTO_INCREMENT COMMENT '主键',
	`name` VARCHAR(20) NOT NULL DEFAULT '0',
	`age` INT(10) NOT NULL DEFAULT '0',
	PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;
INSERT INTO user values(NULL,'冬雨',21);
INSERT INTO user values(NULL,'冬雨',21);
INSERT INTO user values(NULL,'小红',18);
INSERT INTO user values(NULL,'小蓝',21);

在这里插入图片描述

三、User实体类

  • 参照数据库表,完成了实体类的创建。
  • 添加序列号,方便日后在磁盘记录数据。
package com.gql.entity;
import java.io.Serializable;
/**
 * 类说明:
 *		User实体类
 * @guoqianliang1998.
 */
public class User implements Serializable {

	/**
	 * 生成序列号
	 */
	private static final long serialVersionUID = -4492760954899814333L;
	private int id;
	private String name;
	private int age;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

四、业务层Service

  • 真正的开发中,业务层实现类的代码量是很大的,因为需要进行数据校验的工作。

业务层接口UserService

package com.gql.service;

import java.util.List;

import com.gql.entity.User;

/**
 * 类说明:
 *		业务层接口
 * @guoqianliang1998.
 */
public interface UserService {
	void save(User user);

	void update(int id, User user);

	void delete(int id);

	User getUser(int id);

	List<User> getUserList(int[] ids);
	
	List<User> getUserList();
}

业务层实现类UserServiceImp

package com.gql.service;

import java.util.List;

import com.gql.dao.UserDao;
import com.gql.entity.User;
/**
 * 类说明:
 *		业务层实现类
 * @guoqianliang1998.
 */
public class UserServiceImp implements UserService {

	private UserDao userDao;
	
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public void save(User user) {
		userDao.save(user);
	}

	@Override
	public void update(int id, User user) {
		userDao.update(id, user);
	}

	@Override
	public void delete(int id) {
		userDao.delete(id);
	}

	@Override
	public User getUser(int id) {
		User user = userDao.getUser(id);
		return user;
	}

	@Override
	public List<User> getUserList(int[] ids) {
		List<User> userList = userDao.getUserList(ids);
		return userList;
	}

	@Override
	public List<User> getUserList() {
		List<User> list = userDao.getUserList();
		return list;
	}
}

五、数据访问层

  • 数据访问层调用JdbcTemplate完成增删查改操作,值得注意的是查询的操作相对麻烦,尤其是查询[n,m]条记录时,需要谨慎。
  • 尤其要考虑sql语句用的是in还是or,JdbcTemplate对in的支持并不强。如果使用in,则换用NamedParameterJdbcTemplate
    模板。

数据访问层接口

package com.gql.dao;

import java.util.List;

import com.gql.entity.User;

/**
 * 类说明: 
 * 		数据访问层接口 
 * @guoqianliang1998.
 */
public interface UserDao {
	void save(User user);

	void update(int id, User user);

	void delete(int id);

	User getUser(int id);

	List<User> getUserList(int[] ids);
	
	List<User> getUserList();
}

数据访问层实现类

package com.gql.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import com.gql.RowMapper.UserRowMapper;
import com.gql.entity.User;

/**
 * 类说明: 
 * 		数据访问层实现类 
 * @guoqianliang1998.
 */
public class UserDaoImp implements UserDao {
	private JdbcTemplate jdbcTemplate;

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public void save(User user) {
		String sql = "INSERT INTO user values(NULL,?,?)";
		jdbcTemplate.update(sql, user.getName(), user.getAge());
	}

	@Override
	public void update(int id, User user) {
		String sql = "update user set name=?,age=? WHERE id = ?";
		jdbcTemplate.update(sql, user.getName(), user.getAge(), id);
	}

	@Override
	public void delete(int id) {
		String sql = "DELETE FROM user WHERE id = ?;";
		jdbcTemplate.update(sql, id);
	}

	@Override
	public User getUser(int id) {
		String sql = "select * from user where id = ?";
		User user = jdbcTemplate.queryForObject(sql, new RowMapper<User>() {
			@Override
			public User mapRow(ResultSet rs, int rowNum) throws SQLException {
				User user = new User();
				user.setId(rs.getInt(1));
				user.setName(rs.getString(2));
				user.setAge(rs.getInt(3));
				return user;
			}

		}, id);
		return user;
	}

	@Override
	public List<User> getUserList(int[] ids) {
		String sql = "select * from user where id in(:ids)";
		
		NamedParameterJdbcTemplate n = new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource());
		Map<String,Object> paramMap = new HashMap<String,Object>();
		List list = new ArrayList();
		for (int i = 0; i < ids.length; i++) {
			list.add(ids[i]);
		}
		paramMap.put("ids", list);
		List<User> userList = n.query(sql, paramMap, new RowMapper<User>(){
			@Override
			public User mapRow(ResultSet rs, int rowNum) throws SQLException {
				User user = new User();
				user.setId(rs.getInt(1));
				user.setName(rs.getString(2));
				user.setAge(rs.getInt(3));
				return user;
			}
		});
		return userList;
//		第二种写法↓↓↓
//		StringBuilder sb = new StringBuilder();
//		sb.append("SELECT * FROM user WHERE id = ?");
//		for(int i=0;i<ids.length-1;i++){
//			sb.append(" or id = ?");
//		}
//		Integer[] in = new Integer[ids.length];
//		for(int i=0;i<ids.length;i++){
//			in[i] = ids[i];
//		}
//		Object[] args = in;
//		List<User> userList = jdbcTemplate.query(sb.toString(),args,new RowMapper() {
//			
//			@Override
//			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
//				User user = new User();
//				user.setId(rs.getInt(1));
//				user.setName(rs.getString(2));
//				user.setAge(rs.getInt(3));
//				return user;
//			}	
//		});
//		return userList;
	}
	
	@Override
	public List<User> getUserList() {
		String sql = "select * from user";
		List<User> list = jdbcTemplate.query(sql, new UserRowMapper());
		return list;
	}
}

五、实现RowMapper接口对查询结果集重构

除了实现RowMapper接口对查询结果集重构,其实也可以在dao层直接使用匿名内部类,这样就不用自定义实现RowMapper接口了。

package com.gql.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import com.gql.entity.User;
/**
 * 类说明:
 *		使用RowMapper接口对查询结果集重构
 * @guoqianliang1998.
 */
public class UserRowMapper implements RowMapper<User>{

	@Override
	public User mapRow(ResultSet rs, int rowNum) throws SQLException {
		User user = new User();
		user.setId(rs.getInt(1));
		user.setName(rs.getString(2));
		user.setAge(rs.getInt(3));
		return user;
	}
}

六、测试增删查改

所有代码亲测有效,不再贴图。

package com.gql.jdbc;

import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.gql.entity.User;
import com.gql.service.UserService;
/**
 * 类说明:
 *		测试JdbcTemplate的增删改查操作
 * @guoqianliang1998.
 */
public class UserServiceTest {
	/**
	 * 增
	 */
	@Test
	public void testSave() {
		// 加载容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService userService = (UserService) ac.getBean("userService");
		// 模拟数据
		User user = new User();
		user.setName("大力");
		user.setAge(19);
		userService.save(user);
	}

	/**
	 * 删
	 */
	@Test
	public void testDelete() {
		// 加载容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService userService = (UserService) ac.getBean("userService");
		// 模拟数据
		User user = new User();
		user.setName("大力");
		user.setAge(19);
		userService.save(user);
	}
	/**
	 * 改
	 */
	@Test
	public void testUpdate() {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService userService = (UserService) ac.getBean("userService");
		// 模拟数据
		int id = 5;
		userService.delete(id);
	}
	/**
	 * 查,查询全部记录
	 */
	@Test
	public void testGetUserList() {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService userService = (UserService) ac.getBean("userService");
		List<User> userList = userService.getUserList();
		System.out.println(userList.size());
	}
	/**
	 * 查,查询一条记录
	 */
	@Test
	public void testGetUser() {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService userService = (UserService) ac.getBean("userService");
		User user = userService.getUser(2);
		System.out.println(user.getName());
	}
	/**
	 * 查,查询[n,m]条记录
	 */
	@Test
	public void testGetUserList2() {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService userService = (UserService) ac.getBean("userService");
		int[] ids = { 2, 3 };
		List<User> userList = userService.getUserList(ids);
		System.out.println(userList.size());
	}
}
发布了449 篇原创文章 · 获赞 1359 · 访问量 39万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 我行我“速” 设计师: Amelia_0503

分享到微信朋友圈

×

扫一扫,手机浏览