文章目录
Spring JdbcTemplate
- JdbcTemplate是Spring对JDBC的封装,目的是使JDBC更加易于使用。JdbcTemplate是Spring的一部分。JdbcTemplate处理了资源的建立和释放。
常用方法
- execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
- update方法:用于执行新增、修改、删除等语句;
- batchUpdate方法:用于执行批处理相关语句;
- query方法及queryForXXX方法:用于执行查询相关语句;
- call方法:用于执行存储过程、函数相关语句。
数据库连接池
- 数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个;释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏。
案例演示
一、建立数据库
create database simonshop charset=utf8;
use simonshop;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` varchar(20) DEFAULT NULL,
`telephone` varchar(11) DEFAULT NULL,
`register_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`popedom` int(11) DEFAULT NULL COMMENT '0:管理员;1:普通用户',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
INSERT INTO `t_user` VALUES ('1', 'admin', '12345', '15734345678', '2016-12-02 08:40:35', '0');
INSERT INTO `t_user` VALUES ('2', '郑晓红', '11111', '13956567889', '2016-12-20 09:51:43', '1');
INSERT INTO `t_user` VALUES ('3', '温志军', '22222', '13956678907', '2016-12-20 09:52:36', '1');
INSERT INTO `t_user` VALUES ('4', '涂文艳', '33333', '15890905678', '2016-12-05 09:52:56', '1');
二、使用项目SpringDemo2021
链接:https://pan.baidu.com/s/1qQKBxwinlBsx-WBGCcdfng
提取码:1234
三、在pom文件里添加数据库相关依赖
<!--Spring数据库支持-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--数据库驱动工具包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!--数据库连接池框架-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.24</version>
</dependency>
四、创建用户实体类
- 创建相关子包
package net.lj.spring.lesson06.bean;
import java.util.Date;
/**
* 用户实体类
*/
public class User {
private int id;
private String username;
private String password;
private String telephone;
private Date registerTime;
private int popedom;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Date getRegisterTime() {
return registerTime;
}
public void setRegisterTime(Date registerTime) {
this.registerTime = registerTime;
}
public int getPopedom() {
return popedom;
}
public void setPopedom(int popedom) {
this.popedom = popedom;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", telephone='" + telephone + '\'' +
", registerTime=" + registerTime +
", popedom=" + popedom +
'}';
}
}
五、创建用户数据访问接口
- 创建相关子包
package net.lj.spring.lesson06.dao;
import net.lj.spring.lesson06.bean.User;
import java.util.List;
/**
* 用户数据访问接口
*/
public interface UserDao {
int insert(User user);
int deleteById(int id);
int update(User user);
User findById(int id);
List<User> findAll();
User login(String username, String password);
}
六、创建用户数据访问接口实现类
package net.lj.spring.lesson06.dao.impl;
import net.lj.spring.lesson06.bean.User;
import net.lj.spring.lesson06.dao.UserDao;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 用户数据访问接口实现类
*/
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Resource
private JdbcTemplate jdbcTemplate;
/**
* 插入用户表记录
*
* @param user
* @return 插入记录数
*/
public int insert(User user) {
String strSQL = "INSERT INTO t_user (username, password, telephone, register_time, popedom) VALUES (?, ?, ?, ?, ?)";
return jdbcTemplate.update(strSQL, user.getUsername(), user.getPassword(), user.getTelephone(), user.getRegisterTime(), user.getPopedom());
}
/**
* 按编号删除用户记录
*
* @param id
* @return 删除记录数
*/
public int deleteById(int id) {
String strSQL = "DELETE FROM t_user WHERE id = ?";
return jdbcTemplate.update(strSQL, id);
}
/**
* 更新用户记录
*
* @param user
* @return 更新记录数
*/
public int update(User user) {
String strSQL = "UPDATE t_user SET username = ?, password = ?, telephone = ?, register_time = ?, popedom = ? WHERE id = ?";
return jdbcTemplate.update(strSQL, user.getUsername(), user.getPassword(), user.getTelephone(), user.getRegisterTime(), user.getPopedom(), user.getId());
}
/**
* 按编号查询用户记录
*
* @param id
* @return 用户对象
*/
public User findById(int id) {
String strSQL = "SELECT * FROM t_user WHERE id = ?";
return jdbcTemplate.queryForObject(strSQL, new RowMapper<User>() {
// 行映射方法(将用户表记录映射成用户实体)
public User mapRow(ResultSet rs, int row) throws SQLException {
// 创建用户对象
User user = new User();
// 从结果集获取字段值设置用户对象属性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getTimestamp("register_time"));
user.setPopedom(rs.getInt("popedom"));
// 返回用户对象
return user;
}
}, id);
}
/**
* 查询全部用户记录
*
* @return 用户列表
*/
public List<User> findAll() {
String strSQL = "SELECT * FROM t_user";
// 查询获取行列表
List<Map<String, Object>> rows = jdbcTemplate.queryForList(strSQL);
// 创建用户列表
List<User> users = new ArrayList<User>();
// 遍历行列表,生成用户列表
for (Map<String, Object> row : rows) {
// 创建用户对象
User user = new User();
// 从行获取列值设置用户对象属性
user.setId((Integer) row.get("id"));
user.setUsername((String) row.get("username"));
user.setPassword((String) row.get("password"));
user.setTelephone((String) row.get("telephone"));
user.setRegisterTime((Date) row.get("register_time"));
user.setPopedom((Integer) row.get("popedom"));
// 将用户对象添加到用户列表
users.add(user);
}
// 返回用户列表
return users;
}
/**
* 用户登录
*
* @param username
* @param password
* @return 用户实体(null:登录失败,not null:登录成功)
*/
public User login(String username, String password) {
String strSQL = "SELECT * FROM t_user WHERE username = ? AND password = ?";
return jdbcTemplate.queryForObject(strSQL, new RowMapper<User>() {
// 行映射方法(将用户表记录映射成用户实体)
public User mapRow(ResultSet rs, int row) throws SQLException {
// 创建用户对象
User user = new User();
// 从结果集获取字段值设置用户对象属性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getTimestamp("register_time"));
user.setPopedom(rs.getInt("popedom"));
// 返回用户对象
return user;
}
}, username, password);
}
}
七、创建用户服务类
package net.lj.spring.lesson06.service;
import net.lj.spring.lesson06.bean.User;
import net.lj.spring.lesson06.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 用户服务类
*/
@Service("userService")
public class UserService {
@Autowired
private UserDao userDao;
public int addUser(User user) {
return userDao.insert(user);
}
public int deleteUserById(int id) {
return userDao.deleteById(id);
}
public int updateUser(User user) {
return userDao.update(user);
}
public User findUserById(int id) {
return userDao.findById(id);
}
public List<User> findAllUsers() {
return userDao.findAll();
}
public User login(String username, String password) {
return userDao.login(username, password);
}
}
八、创建数据库配置属性文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/simonshop?useSSL=false
jdbc.username=root
jdbc.password=123456 #mysql密码
九、创建Spring配置文件
<?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.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--组件扫描-->
<context:component-scan base-package="net.lj.spring.lesson06"/>
<!--声明属性占位符-->
<context:property-placeholder location="jdbc.properties"/>
<!--定义数据源Bean-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--定义JDBC模板Bean-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
十、创建用户服务测试类
package net.lj.spring.lesson06.service;
import net.lj.spring.lesson06.bean.User;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Date;
import java.util.List;
public class TestUserService {
private UserService userService;
private ClassPathXmlApplicationContext context;
@Before
public void init() {
context = new ClassPathXmlApplicationContext("jdbc/spring-config.xml");
userService = (UserService) context.getBean("userService");
}
/**
* 按编号查询用户
*/
@Test
public void testFindUserById() {
try {
User user = userService.findUserById(2);
System.out.println(user);
} catch (Exception e) {
System.out.println("记录未找到!");;
}
}
/**
*查询所有用户
*/
@Test
public void testFindAllUsers() {
List<User> users = userService.findAllUsers();
for (User user : users) {
System.out.println(user);
}
}
/**
*添加用户
*/
@Test
public void testAddUser() {
User user = new User();
user.setUsername("李小文");
user.setPassword("12345");
user.setTelephone("15890903345");
user.setRegisterTime(new Date());
user.setPopedom(1);
int count = userService.addUser(user);
if (count > 0) {
System.out.println("添加用户成功!");
} else {
System.out.println("添加用户失败!");
}
}
/**
*更新用户
*/
@Test
public void testUpdateUser() {
User user = userService.findUserById(5);
System.out.println("更新前:" + user);
user.setUsername("钟晓丽");
user.setPassword("55555");
user.setTelephone("13990903345");
user.setRegisterTime(new Date());
user.setPopedom(0);
int count = userService.updateUser(user);
if (count > 0) {
System.out.println("更新用户成功!");
System.out.println("更新后:" + userService.findUserById(5));
} else {
System.out.println("更新用户失败!");
}
}
/**
*删除用户
*/
@Test
public void testDeleteUserById() {
int count = userService.deleteUserById(5);
if (count > 0) {
System.out.println("删除用户成功!");
} else {
System.out.println("删除用户失败!");
}
}
/**
*用户登录
*/
@Test
public void testLogin() {
String username = "郑晓红";
String password = "11111";
try {
User user = userService.login(username, password);
System.out.println("恭喜,登录成功!");
} catch (Exception e) {
System.out.println("遗憾,登录失败!");
}
}
@After
public void destroy() {
context.close();
}
}