手撕Spring5框架(八)操作JdbcTemplate

什么是JdbcTemplate?

Spring 框架对JDBC进行封装,使用JDBCTemplate方便实现对数据库的才做。

如何使用jdbcTemplate?

准备工作

  • 引用jar包  
 

        
            org.springframework
            spring-jdbc
            5.2.8.RELEASE
        

        
            org.springframework
            spring-orm
            5.2.8.RELEASE
        

        
            org.springframework
            spring-tx
            5.2.8.RELEASE
        
        
        
        
            mysql
            mysql-connector-java
            8.0.13
        

        
        
            com.alibaba
            druid
            1.1.14
        
  • 配置数据库连接池

    
       
	
    
        
        
        
        
    
  • 配置jdbcTemplate对象,注入DataSource

    
        
        
    
  • 创建jdbc.properties
prop.driverClass=com.mysql.cj.jdbc.Driver
prop.url=jdbc:mysql://127.0.0.1:3306/spring5-demo?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&zeroDateTimeBehavior=CONVERT_TO_NULL
prop.userName=root
prop.password=123456
  • 创建service类,dao类,在dao类注入jdbcTemplate对象
package org.learn.spring5.service.impl;

import org.learn.spring5.dao.impl.UserDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    //注入UserDao的对象
    @Autowired
    private UserDaoImpl userDao;

}

 

package org.learn.spring5.dao.impl;

import org.learn.spring5.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

public class UserDaoImpl implements UserDao{

    //注入JdbcTemplate對象
    @Autowired
    private JdbcTemplate jdbcTemplate;
}
  • 编写实体类User
package org.learn.spring5.entiy;

public class User {
    //id
    private Integer id;
    //用户名
    private String userName;
    //用户状态
    private Integer status;

    public Integer getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }
}
  •  创建数据和表结构
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (
  `id` int(11) NOT NULL,
  `user_name` varchar(22) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `status` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

具体操作

  • JdbcTemplate操作数据库-添加功能

1)在UserDaoImpl类里添加add方法

2)调用JdbcTemplate对象的update方法

package org.learn.spring5.dao.impl;

import org.learn.spring5.entiy.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class UserDaoImpl implements UserDao{

    //注入JdbcTemplate對象
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void add(User user) {
        //1.創建sql語句
        String sql="insert into t_user values(?,?,?)";
        //2.調用方法实现
        Object[] args={user.getId(),user.getUserName(),user.getStatus()};
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }
}

3)编写测试程序

import org.junit.Test;
import org.learn.spring5.entiy.User;
import org.learn.spring5.service.impl.UserService;
import org.learn.spring5.service.impl.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5 {
    /**
     * 操作JdbcTemplate,添加操作
     */
    @Test 
    public void testAdd() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userServiceImpl", UserServiceImpl.class);
        User user = new User();
        user.setId(1);
        user.setUserName("张三");
        user.setStatus(1);
        userService.addUser(user);

    }


}

程序返回结果1,标识数据添加成功!

  • JdbcTemplate操作数据库-修改功能
public int update(User user) {
        String sql = "update t_user set user_name =?,status=? where id =?";
        Object[] args = {user.getUserName(), user.getStatus(), user.getId()};
        int update = jdbcTemplate.update(sql, args);

        return update;
    }

编写测试程序

   //JdbcTemplate修改操作
    @Test
    public void testUpdate() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userServiceImpl", UserServiceImpl.class);
        User user = new User();
        user.setId(1);
        user.setUserName("张四");
        user.setStatus(0);
        userService.update(user);
    }
  • JdbcTemplate操作数据库-查询功能

1)查询返回某一个值

 public int queryCount() {
        String sql = "select count(*) from t_user";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }

编写测试程序

//JdbcTemplate 查询操作,返回用户的数量
    @Test
    public void testQueryCount() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userServiceImpl", UserServiceImpl.class);
        int count = userService.queryCount();
        System.out.println(count);
    }

2)查询返回对象

public User findOne(Integer id) {
        String sql = "select * from t_user where id =?";
        User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper(User.class), id);
        return user;
    }

编写测试程序

 //JdbcTemplate 查询操作,返回对象根据id
    @Test
    public void testQueryById() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userServiceImpl", UserServiceImpl.class);
        User user = userService.queryById(1);
        System.out.println(user);
    }

3)查询返回集合

//JdbcTemplate 查询操作,返回集合对象
    @Test
    public void testFindAll() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userServiceImpl", UserServiceImpl.class);
        List all = userService.findAll();
        System.out.println(all);
    }

编写测试程序

  //JdbcTemplate 查询操作,返回集合对象
    @Test
    public void testFindAll() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userServiceImpl", UserServiceImpl.class);
        List all = userService.findAll();
        System.out.println(all);
    }
  • JdbcTemplate操作数据库-删除功能
 public int del(Integer id) {
        String sql = "delete from t_user where id =?";
        int update = jdbcTemplate.update(sql, id);
        return update;
    }

编写测试程序

 //JdbcTemplate删除操作
    @Test
    public void testDel() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userServiceImpl", UserServiceImpl.class);
        userService.del(1);
    }
  • JdbcTemplate操作数据库-批量添加
    public void batchAdd(List users) {
        String sql = "insert into t_user values(?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql, users);
        System.out.println(Arrays.asList(ints));

    }

编写测试程序

  //JdbcTemplate 批量添加操作
    @Test
    public void batchAdd() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userServiceImpl", UserServiceImpl.class);
        List list = new ArrayList();
        Object[] o1 = {"4","name1",0};
        Object[] o2 = {"5","name2",0};
        Object[] o3 = {"6","name3",0};
        list.add(o1);
        list.add(o2);
        list.add(o3);
        userService.batchAdd(list);
    }
  • JdbcTemplate操作数据库-批量修改和删除
//批量修改操作
  public void batchUpdate(List users) {
        String sql = "update t_user set user_name =?,status=? where id =?";
        int[] ints = jdbcTemplate.batchUpdate(sql, users);
        System.out.println(Arrays.asList(ints).toString());

    }
//批量删除操作
    public void batchDel(List users) {
        String sql = "delete from t_user where id =?";
        int[] ints = jdbcTemplate.batchUpdate(sql, users);
        System.out.println(ints);
    }

编写测试程序

//JdbcTemplate 批量修改操作
    @Test
    public void batchUpdate() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userServiceImpl", UserServiceImpl.class);
        List list = new ArrayList();
        Object[] o1 = {"namexiugai", 1, 4};
        Object[] o2 = {"name2xiugai", 1, 5};
        Object[] o3 = {"name3xiugai", 1, 6};
        list.add(o1);
        list.add(o2);
        list.add(o3);
        userService.batchUpdate(list);
    }

    //JdbcTemplate 批量删除操作
    @Test
    public void batchDel() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userServiceImpl", UserServiceImpl.class);
        List list = new ArrayList();
        Object[] o1 = {4};
        Object[] o2 = {5};
        Object[] o3 = {6};
        list.add(o1);
        list.add(o2);
        list.add(o3);
        userService.batchDel(list);
    }

 

你可能感兴趣的:(手撕Spring5框架,spring,java,后端)