这篇文章主要介绍了Spring5之JDBC使用案例,通过JDBC使用案例来了解Spring是如何访问数据库。需要的朋友可以参考一下。
1、创建数据表结构
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
`sex` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
2、创建对应数据表的PO
package com.test.jdbc.po;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Description: 用户实体类
* @Author: Janson
* @Date: 2020/5/2 19:33
**/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private int age;
private String sex;
}
3、创建表与实体间的映射
package com.test.jdbc.mapper;
import com.test.jdbc.po.User;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @Description: 用户实体与表的映射
* @Author: Janson
* @Date: 2020/5/2 19:35
**/
public class UserRowMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User(rs.getInt("id"), rs.getString("name"), rs.getInt("age"), rs.getString("sex"));
return user;
}
}
4、创建数据操作接口
package com.test.jdbc.service;
import com.test.jdbc.po.User;
import java.util.List;
/**
* @Description: 用户服务类接口
* @Author: Janson
* @Date: 2020/5/2 22:53
**/
public interface UserService {
/**
* 保存用户
* @param user
*/
void save(User user);
/**
* 获取用户列表
* @return
*/
List<User> getUsers();
}
5、创建数据操作接口实现类
package com.test.jdbc.service.impl;
import com.test.jdbc.mapper.UserRowMapper;
import com.test.jdbc.po.User;
import com.test.jdbc.service.UserService;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.sql.Types;
import java.util.List;
/**
* @Description: 用户服务实现类
* @Author: Janson
* @Date: 2020/5/2 23:01
**/
public class UserServiceImpl implements UserService {
private JdbcTemplate jdbcTemplate;
// 设置数据源
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public void save(User user) {
jdbcTemplate.update("insert into user(name,age,sex) values (?,?,?)",
new Object[]{user.getName(), user.getAge(), user.getSex()},
new int[]{Types.VARCHAR, Types.INTEGER, Types.VARCHAR});
}
@Override
public List<User> getUsers() {
List<User> list = jdbcTemplate.query("select * from user", new UserRowMapper());
return list;
}
}
6、创建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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置数据源-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/user?serverTimezone=Asia/Shanghai" />
<property name="username" value="root" />
<property name="password" value="123456" />
<!--连接池启动时初始值-->
<property name="initialSize" value="1" />
<!--连接池的最大值-->
<property name="maxActive" value="300" />
<!--最大空闲值,当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止-->
<property name="maxIdle" value="2"/>
<!--最小空闲值,当空闲的连接数少于阀值时,连接池就会预申请一些连接,以免洪峰来时来不及申请-->
<property name="minIdle" value="1"/>
</bean>
<!--配置业务bean-->
<bean id="userService" class="com.test.jdbc.service.impl.UserServiceImpl">
<!--向属性注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
7、测试
package com.test;
import com.test.jdbc.po.User;
import com.test.jdbc.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
/**
* @Description: spring jdbc test
* @Author: Janson
* @Date: 2020/5/2 23:39
**/
@Slf4j
public class SpringJDBCTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("datasource.xml");
UserService userService = (UserService) applicationContext.getBean("userService");
User user = new User();
user.setName("张三");
user.setAge(20);
user.setSex("男");
// 保存一条记录
userService.save(user);
List<User> users = userService.getUsers();
log.info("从数据库取得所有的users:{}", users);
users.forEach(item -> {
log.info("user id:{} name:{} age:{} sex:{}", item.getId(), item.getName(), item.getAge(), item.getSex());
});
}
}
8、测试输出结果
23:58:05.499 [main] INFO com.test.SpringJDBCTest - 从数据库取得所有的users:[User(id=4, name=张三, age=20, sex=男)]
23:58:05.500 [main] INFO com.test.SpringJDBCTest - user id:4 name:张三 age:20 sex:男
如果您觉得有帮助,欢迎点赞收藏哦 ~ ~ 多谢~