第八章:SpringBoot2.3.0 JdbcTemplate和NamedParameterJdbcTemplate使用详解

一)JdbcTemplate简介

Spring JdbcTemplate是对jdbc API的一些封装,也可以说JdbcTemplate是Spring MVC内置的对JDBC的一个封装。

优点:执行效率快,和jdbc一样,适合大批量数据操作。

缺点:事务处理方面没有mybatis和hibernate、jpa完善。

 

二)JdbcTemplate使用

第一步:在oracle数据库中创建一个表,用于数据持久化保持,脚本如下:

drop table TAB_EMPLOYEE;

create table TAB_EMPLOYEE
(
  emp_id      NUMBER,
  emp_name    VARCHAR2(100),
  emp_no      VARCHAR2(100),
  create_date NUMBER
);

delete from TAB_EMPLOYEE;

select count(0) from TAB_EMPLOYEE;

select * from TAB_EMPLOYEE;

 

第二步:创建一个maven项目,在pom.xml中引入springboot需要的jar包

注:如果oracle的jar引入报错,需要先到网上自行下载一个ojdbc6.jar包,然后执行下面一句命令。

命令:mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -Dfile=E:\dev\jar\ojdbc6.jar

pom.xml配置:



    4.0.0

    com.oysept
    jdbctemplate_springboot
    1.0-SNAPSHOT
    jar

    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.0.RELEASE
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-jdbc
        

        
        
            com.oracle
            ojdbc6
            11.2.0.3
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

项目结构图如下:

第八章:SpringBoot2.3.0 JdbcTemplate和NamedParameterJdbcTemplate使用详解_第1张图片

 

第三步:创建一个application.yml,添加oracle的连接配置

server:
  port: 8080

spring:
  datasource:
    url: jdbc:oracle:thin:@localhost:1521:ORCL
    username: oysept
    password: orcl
    driver-class-name: oracle.jdbc.driver.OracleDriver

 

第四步:创建SpringBoot启动类,和一个User实体类

JdbcTemplateApplication.java启动类:

package com.oysept;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class JdbcTemplateApplication {

    public static void main(String[] args) {
        SpringApplication.run(JdbcTemplateApplication.class, args);
    }
}

User.java实体类:

package com.oysept.bean;

/**
 * 员工表
 * @author ouyangjun
 */
public class User {
	
    private Integer empId;
    private String empName;
    private String empNO;
    private Long createDate;

    public User() {}
    public User(Integer empId, String empName, String empNO, Long createDate) {
        this.empId = empId;
        this.empName = empName;
        this.empNO = empNO;
        this.createDate = createDate;
    }

    public Integer getEmpId() {return empId;}
    public void setEmpId(Integer empId) {this.empId = empId;}

    public String getEmpName() {return empName;}
    public void setEmpName(String empName) {this.empName = empName;}

    public String getEmpNO() {return empNO;}
    public void setEmpNO(String empNO) {this.empNO = empNO;}

    public Long getCreateDate() {return createDate;}
    public void setCreateDate(Long createDate) {this.createDate = createDate;}
    
    public String toString() {
        return "User[empId:" + this.empId + ", empName:" + this.empName
                + ", empNO:" + this.empNO + ", createDate:" + this.createDate + "]";
    }
}

 

第五步:创建一个测试Controller类

package com.oysept.controller;

import com.oysept.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
public class JdbcTemplateController {

    // jdbc操作工具类
    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 使用名称占位符工具类
    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

}

 

新增User:jdbcTemplate.update()方法可以执行insertupdatedelete等语句

/**
 * 新增用户信息
 * 访问地址: http://localhost:8080/jdbc/insertUser
 */
@RequestMapping(value="/jdbc/insertUser")
public Integer insertUser() {
    String sql = "insert into TAB_EMPLOYEE(emp_id, emp_name, emp_no, create_date) values (?, ?, ?, ?)";
    int count = jdbcTemplate.update(sql, 111, "aaaa", "hhhh", new Date().getTime());
    return count;
}

 

批量新增User:使用?占位符

/**
  * 批量新增用户信息, ?占位符方式
 * 访问地址: http://localhost:8080/jdbc/batchInsertUser
 */
@RequestMapping(value="/jdbc/batchInsertUser")
public Integer batchInsertUser() {
    List list = new ArrayList();
    String sql = "insert into TAB_EMPLOYEE(emp_id, emp_name, emp_no, create_date) values (?, ?, ?, ?)";
    for (int i=0; i<10; i++) {
        list.add(new Object[]{i, "aaa" + i, "bbb" + i, new Date().getTime()});
    }
    int[] count = jdbcTemplate.batchUpdate(sql, list);
    return count.length;
}

 

批量新增User:使用“:name”占位符

注:占位符的名称需要和实体类中属性名一致

/**
 * 批量新增用户信息, 占位符方式
 * 访问地址: http://localhost:8080/jdbc/batchInsertUserByNamed
 */
@RequestMapping(value="/jdbc/batchInsertUserByNamed")
public Integer batchInsertUserByNamed() {
    List list = new ArrayList();
    String sql = "insert into TAB_EMPLOYEE(emp_id, emp_name, emp_no, create_date) values (:empId, :empName, :empNO, :createDate)";
    for (int i=0; i<10; i++) {
        list.add(new User(i, "aaa" + i, "bbb" + i, new Date().getTime()));
    }
    SqlParameterSource[] beanSources = SqlParameterSourceUtils.createBatch(list.toArray());
    int[] count = namedParameterJdbcTemplate.batchUpdate(sql, beanSources);
    return count.length;
}

 

查询User:

/**
 * 返回List>
 * 访问地址: http://localhost:8080/jdbc/listUser
 */
@RequestMapping(value="/jdbc/listUser")
public List> listUser() {
    String sql = "select emp_id, emp_name, emp_no, create_date from TAB_EMPLOYEE";
    List> list = jdbcTemplate.queryForList(sql);
    list.stream().forEach(x->{
        System.out.println("listUser==> emp_id: " + x.get("EMP_ID")
            + ", emp_name" + x.get("EMP_NAME"));
    });
    return list;
}

 

识别二维码关注个人微信公众号

本章完结,待续,欢迎转载!
 
本文说明:该文章属于原创,如需转载,请标明文章转载来源!

你可能感兴趣的:(SpringBoot2.3.0)