Spring整合JDBCTemplate

  1. 什么是JDBCTemplate?

    1. Spring框架对JDBC进行封装,使用JDBCTemplate方便实现对数据的操作
  2. 准备工作

    1. 引入相关的依赖

    2. 在Spring配置文件配置数据库连接池

      <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
          <property name="url" value="jdbc:mysql://localhost:3306"/>
          <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
          <property name="username" value="root"/>
          <property name="password" value="154269564"/>
      </bean>
      
    3. 配置JDBCTemplate对象,注入dataSource

      <!--    jdbcTemplate对象-->
          <bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
      <!--        注入dataSource-->
      <!--        JdbcTemplate源码中,使用的set注入-->
              <property name="dataSource" value="dataSource"/>
          </bean>
      
    4. 创建service类,创建dao类,在dao注入jdbcTemplate对象

      1. application.xml配置文件

        <!--    开启组件扫描-->
            <context:component-scan base-package="com.qi"></context:component-scan>
        
      2. Dao

        public interface BookDao {
        
        }
        
        @Repository
        public class BookDaoImpl implements BookDao{
            //注入jdbcTemplate
            @Autowired
            JdbcTemplate jdbcTemplate;
        }
        
      3. Service

        @Service
        public class BookService {
            //注入Dao
            @Autowired
            BookDao bookDo;
        }
        

    JDBCTempl操作数据库(添加)

    1. 对应数据库创建实体类

      @Data
      @AllArgsConstructor
      @NoArgsConstructor
      public class User {
          private int userId;
          private String username;
          private String ustatus;
      }
      
    2. 编写Service和Dao

      1. 在dao进行数据库添加操作

      2. 调用JDBCTemplate对象中的update方法实现添加操作
        在这里插入图片描述

        • 有两个参数
        • 第一个参数,sql语句
        • 第二个参数:可变参数,设置sql语句值
      public interface UserDao {
          public void add(User user);
      }
      
      @Repository
      public class UserDaoImpl implements UserDao {
          //注入jdbcTemplate
          @Autowired
          JdbcTemplate jdbcTemplate;
      
          public void add(User user) {
              //创建sql语句
              String string = "insert into t_user values(?,?,?)";
      //        //调用方法实现
              Object[] args = {user.getUserId(),user.getUsername(),user.getUstatus()};//可变参数
              int update = jdbcTemplate.update(string, args);
      
              System.out.println(update);
          }
      
      }
      
      public interface UserService {
          public void add(User user);
      }
      
      @Service("UserService")//变为一个UserService的bean
      public class UserServiceImpl implements UserService{
      
          @Autowired
          UserDao userDao;
      
          public void add(User user) {
              userDao.add(user);
          }
      }
      
    3. 测试类

      public class TestDemo {
          @Test
          public void TestUser(){
              ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
              UserServiceImpl userService = context.getBean("UserService", UserServiceImpl.class);
              User user = new User();
              user.setUserId(Integer.parseInt("3"));
              user.setUsername("zhangsan");
              user.setUstatus("a");
              userService.add(user);
          }
      }
      

    JDBCTempl操作数据库(添加)

    public void update(User user) {//修改
        //创建sql语句
        String string = "update t_user set username=?,ustatus=? where user_id=?";
        //调用方法实现
        Object[] args = {user.getUsername(),user.getUstatus(),user.getUserId()};//可变参数
        int update = jdbcTemplate.update(string, args);
        System.out.println(update);
    }
    
    public void delete(int id) {//删除
        //创建sql语句
        String string = "delete from t_user where user_id=?";
        //调用方法实现
        int delete = jdbcTemplate.update(string, id);
        System.out.println(delete);
    }
    

    测试类:

    @Test
    public void Test_Update(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserServiceImpl userService = context.getBean("UserService", UserServiceImpl.class);
        User user = new User();
        user.setUserId(Integer.parseInt("3"));
        user.setUsername("lisi");
        user.setUstatus("b");
        userService.update(user);
    }
    @Test
    public void Test_Delete(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserServiceImpl userService = context.getBean("UserService", UserServiceImpl.class);
        userService.delete(2);
    }
    

    JDBCTempl操作数据库(查询返回某个值)

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FyTxchjw-1593745790603)(Spring.assets/image-20200703004159898.png)]

    • 两个参数
    • 参数1:sql语句
    • 参数2:返回类型Class
    //查询表中的记录数
    public int selectCount() {
        String sql = "select count(*) from t_user";
        Integer query = jdbcTemplate.queryForObject(sql, Integer.class);
        return query;
    }
    
    @Test
    public void Test_Query(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserServiceImpl userService = context.getBean("UserService", UserServiceImpl.class);
        int count = userService.selectCount();
        System.out.println(count);
    }
    

    JDBCTempl操作数据库(查询返回对象)

    1. 场景:查询图书详情(返回一个Book对象)
    2. JDBCTempl实现查询返回对象

在这里插入图片描述

  • 三个参数
  • 参数1:sql语句
  • 参数2:RowMapper,是一个接口,返回不同类型数据,时用这个接口里面实现类完成数据的封装
  • 参数3:可变参数,sql语句值
public User findUser(int id) {
    String sql = "select * from t_user where user_id=?";
    User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id);
    return user;
}
@Test
public void Test_findUser(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserServiceImpl userService = context.getBean("UserService", UserServiceImpl.class);
    User user = userService.findUser(1);
    System.out.println(user);
}

JDBCTempl操作数据库(查询返回集合)

  1. 场景:查询图书列表分页

  2. JDBCTempl实现查询返回集合

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KwhwZNeo-1593745790611)(Spring.assets/image-20200703005748274.png)]

    • 三个参数:
    • 参数1:sql语句
    • 参数2:RowMapper,是一个接口,返回不同类型数据,时用这个接口里面实现类完成数据的封装
    • 参数3;sql语句值,可以省略不写
public List<User> findAllUser() {
    String sql = "select * from t_user";
    List<User> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
    return query;
}
@Test
public void Test_findAllUser(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserServiceImpl userService = context.getBean("UserService", UserServiceImpl.class);
    List<User> allUser = userService.findAllUser();
    System.out.println(allUser);
}

JdbcTemplate 操作数据库(批量操作)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章