Spring 框架对 JDBC 进行封装,使用 JdbcTemplate 方便实现对数据库操作
1.准备工作
(1)引入相关 jar 包
(2)配置xml文件
1.在 spring 配置文件配置数据库连接池
2.配置 JdbcTemplate 对象,注入 DataSource
3.组件扫描
<?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 http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1.数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="jdbc:mysql://localhost/user_db"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
</bean>
<!--2.配置 JdbcTemplate 对象,注入 DataSource-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入 dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 组件扫描 -->
<context:component-scan base-package="test10"></context:component-scan>
</beans>
(3)创建 service 类,创建 dao 类,在service里注入dao,在 dao 里注入 jdbcTemplate 对象
@Service
public class UserService {
@Autowired
private UserDao userDao;
}
@Repository
public class UserDaoImpl implements UserDao{
@Autowired
private JdbcTemplate jdbcTemplate;
}
2. JdbcTemplate 操作数据库(添加)
1.首先在数据库中建立个user表
样式如下:
2.创建对应数据库的实体类
User类:
public class User {
private String userId;
private String username;
private int userage;
public User() {
}
public User(String userId, String username, int userage) {
this.userId = userId;
this.username = username;
this.userage = userage;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getUserage() {
return userage;
}
public void setUserage(int userage) {
this.userage = userage;
}
@Override
public String toString() {
return "User{" +
"userId='" + userId + '\'' +
", username='" + username + '\'' +
", userage=" + userage +
'}';
}
}
3.编写 service 和 dao
(1)在 dao 进行数据库添加操作
(2)调用 JdbcTemplate 对象里面 update 方法实现添加操作
UserDao:
public interface UserDao {
void add(User user);
}
UserDaoImpl:
@Repository
public class UserDaoImpl implements UserDao{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void add(User user) {
//1 创建 sql 语句
String sql = "insert into t_user values(?,?,?)";
//2 调用方法实现
int update = jdbcTemplate.update(sql, user.getUserId(), user.getUsername(), user.getUserage());
System.out.println(update);//上一步的返回值为影响的行数
}
}
UserService:
@Service
public class UserService {
@Autowired
private UserDao userDao;
//添加一个用户
public void addUser(User user){
userDao.add(user);
}
}
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="jdbc:mysql://localhost:3306/user_db?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
</bean>
<!--配置 JdbcTemplate 对象,注入 DataSource-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入 dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 组件扫描 -->
<context:component-scan base-package="test10"></context:component-scan>
</beans>
测试类:
@Test
public void test01(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test10/bean.xml");
UserService userService = context.getBean("userService", UserService.class);
User user = new User();
user.setUserId("2");
user.setUsername("Amy");
user.setUserage(19);
userService.addUser(user);
}
实验结果:
下面为addUser方法的时序图:
3. JdbcTemplate 操作数据库(修改和删除)
修改、删除操作与上面的添加操作类似,只需在Userdao、UserImpl、Userservice中添加相应的方法,并修改sql语句即可。
sql语句分别为:
- 修改:
String sql = "update t_user set username=?,userage=? where user_id=?";
- 删除:
String sql = "delete from t_user where user_id=?";
4. JdbcTemplate 操作数据库(查询返回某个值)
1、查询表里面有多少条记录,返回是某个值
2、使用 JdbcTemplate 实现查询返回某个值方法:
有两个参数
- 第一个参数:sql 语句
- 第二个参数:返回类型 Class
UserDao:
public interface UserDao {
int selectCount();
}
UserDaoImpl:
@Repository
public class UserDaoImpl implements UserDao{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public int selectCount() {
String sql = "select count(*) from t_user";
Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
return count;
}
}
UserService:
@Service
public class UserService {
@Autowired
private UserDao userDao;
//查询表记录
public int selectCount(){
return userDao.selectCount();
}
}
xml配置文件与上面的相同
测试类:
@Test
public void test03(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test10/bean.xml");
UserService userService = context.getBean("userService", UserService.class);
System.out.println("表中的记录条数:" + userService.selectCount());
}
实验结果:
5.JdbcTemplate 操作数据库(查询返回对象)
1、场景:查询图书详情
2、JdbcTemplate 实现查询返回对象方法:
有三个参数 :
- 第一个参数:sql 语句
- 第二个参数:RowMapper 是接口,针对返回不同类型数据,使用这个接口里面实现类完成数据封装
- 第三个参数:sql 语句值
UserDao:
public interface UserDao {
User findInfo(String id);
}
UserDaoImpl:
@Repository
public class UserDaoImpl implements UserDao{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public User findInfo(String id) {
String sql = "select * from t_user where user_id=?";
User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
return user;
}
}
UserService:
@Service
public class UserService {
@Autowired
private UserDao userDao;
//查询返回对象
public User findUserById(String id){
return userDao.findInfo(id);
}
}
xml配置文件与上面的相同
测试类:
@Test
public void test04(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test10/bean.xml");
UserService userService = context.getBean("userService", UserService.class);
System.out.println(userService.findUserById("1"));
}
实验结果:
6. JdbcTemplate 操作数据库(查询返回集合)
1、场景:查询图书列表分页…
2、调用 JdbcTemplate 方法实现查询返回集合:
有三个参数 :
- 第一个参数:sql 语句
- 第二个参数:RowMapper 是接口,针对返回不同类型数据,使用这个接口里面实现类完成
数据封装 - 第三个参数:sql 语句值
UserDao:
public interface UserDao {
List<User> findALL();
}
UserDaoImpl:
@Repository
public class UserDaoImpl implements UserDao{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<User> findALL() {
String sql = "select * from t_user";
List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
return userList;
}
}
UserService:
@Service
public class UserService {
@Autowired
private UserDao userDao;
//查询用户列表
public List<User> findALLUser(){
return userDao.findALL();
}
}
xml配置文件与上面的相同
测试类:
@Test
public void test05(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test10/bean.xml");
UserService userService = context.getBean("userService", UserService.class);
List<User> allUser = userService.findALLUser();
for (Object obj: allUser) {
System.out.println(obj);
}
}
实验结果:
7.JdbcTemplate 操作数据库(批量操作)
1、批量操作:操作表里面多条记录
2、JdbcTemplate 实现批量添加操作:
有两个参数 :
- 第一个参数:sql 语句
- 第二个参数:List 集合,添加多条记录数据
UserDao:
public interface UserDao {
void batchAdd(List<Object[]> users);
}
UserDaoImpl:
@Repository
public class UserDaoImpl implements UserDao{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void batchAdd(List<Object[]> users) {
String sql = "insert into t_user values(?,?,?)";
int[] ints = jdbcTemplate.batchUpdate(sql, users);
System.out.println(Arrays.toString(ints));
}
}
UserService:
@Service
public class UserService {
@Autowired
private UserDao userDao;
//批量添加
public void batchAddUser(List<Object[]> users){
userDao.batchAdd(users);
}
}
xml配置文件与上面的相同
测试类:
@Test
public void test06(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test10/bean.xml");
UserService userService = context.getBean("userService", UserService.class);
//批量添加测试
ArrayList<Object[]> list = new ArrayList<>();
Object[] o1 = {"3","Eva",15};
Object[] o2 = {"4","Bander","56"};
Object[] o3 = {"5","Hemy","35"};
list.add(o1);
list.add(o2);
list.add(o3);
userService.batchAddUser(list);
}
实验结果:
8. JdbcTemplate 操作数据库(批量修改和删除)
批量修改、批量删除操作与上面的批量添加操作类似,只需在Userdao、UserImpl、Userservice中添加相应的方法,并修改sql语句即可。