spring-boot-route (7) integrate jdbcTemplate operation database

In part of the content, we learned the preparation of the Restful interface and the generation of interface documentation. We need to store interface data persistently. In this part, we mainly learn several persistent frameworks to store data. In this section, we will use mysql as an example as a demonstration database.

When we first started contacting database operations, we would use JDBC for database operations, but every time we have to create a connection, it is very troublesome to close the connection. Spring simply encapsulates JDBC into a new framework-JdbcTemplate.

Project construction

1 Add mysql dependency

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.11</version>
</dependency>

2. Add jdbcTemplate dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

3. Configure mysql

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/simple_fast?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&useAffectedRows=true&allowPublicKeyRetrieval=true
    username: root
    password: root

Simple operation database

Create a new table studentto test the common functions of JdbcTemplate. The table statement is as follows:

CREATE TABLE `student` (
   `student_id` int(30) NOT NULL,
   `age` int(1) DEFAULT NULL COMMENT '年龄',
   `name` varchar(45) DEFAULT NULL COMMENT '姓名',
   `sex` int(1) DEFAULT NULL COMMENT '性别:1:男,2:女,0:未知',
   `create_time` datetime DEFAULT NULL COMMENT '创建时间',
   `status` int(1) DEFAULT NULL COMMENT '状态:1:正常,-1:删除',
   PRIMARY KEY (`student_id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='学生表'

The corresponding entity classes are as follows:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class StudentBean implements Serializable {

    private static final long serialVersionUID = 4618004018169112427L;

    private Integer studentId;
    private Integer age;
    private String name;
    private Integer sex;
    private Date createTime;
    private Integer status;
}

JdbcTemplate provides a relatively complete database operation API. The commonly used APIs in daily development mainly fall into two categories, namely

  • query与queryXXX
  • update与batchUpdate

The use of JdbcTemplate is also very simple, where injection can be used

@Autowired
private JdbcTemplate jdbcTemplate;

1 Query a single entity

public StudentBean getStudent(int status){
    String sql = "select * from student where status = ? limit 1";
    return jdbcTemplate.queryForObject(sql,new Object[]{status},new BeanPropertyRowMapper<>(StudentBean.class));
}

2 Query the List collection

public List<StudentBean> studentBeanList(int status){
    String sql = "select * from student where status = ?";
    return  jdbcTemplate.query(sql,new Object[]{status},new BeanPropertyRowMapper<>(StudentBean.class));
}

3. Delete operation

public int deleteStudent(int status){
    String sql = "delete from student where status = 0";
    return jdbcTemplate.update(sql);
}

4. Update operation

public int updateStudent(int studentId,String name){
    String sql = "update student set name = ? where student_id = ?";
    return jdbcTemplate.update(sql,new Object[]{name,studentId});
}

5. Insert operation

public int addStudent(){
    String sql = "insert into student(student_id,age,name,status) values(?,?,?,?)";
    return jdbcTemplate.update(sql,new Object[]{30,18,"Java旅途",0});
}

6. Bulk Insert

JdbcTemplate provides APIs for batch insertion. In order to reduce operations with the database and improve insertion efficiency, the data to be inserted is placed in the buffer in batches, and multiple pieces of data are inserted in a batch.

public int batchAddStudent(){

    // 构造list集合
    List<StudentBean> studentBeanList = new ArrayList<>();
    StudentBean studentBean = new StudentBean(31, 31, "Java旅途", 1, new Date(), 1);
    StudentBean studentBean1 = new StudentBean(32, 32, "javatrip", 1, new Date(), 1);
    studentBeanList.add(studentBean);
    studentBeanList.add(studentBean1);
    String sql = "insert into student values(?,?,?,?,?,?)";

    int[] ints = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            StudentBean student = studentBeanList.get(i);
            ps.setInt(1, student.getStudentId());
            ps.setInt(2, student.getAge());
            ps.setString(3, student.getName());
            ps.setInt(4, student.getSex());
            ps.setDate(5,new java.sql.Date(System.currentTimeMillis()));
            ps.setInt(6, student.getStatus());
        }

        @Override
        public int getBatchSize() {
            return studentBeanList.size();
        }
    });
    return ints.length;
}

The above just demonstrate a few simple examples, if you need more detailed usage, you can refer to the official JdbcTemplate API. JdbcTemplate is a relatively easy framework for beginners, and it is also very convenient to use. But there are some shortcomings. It hard-codes sql into java code. If you need to modify sql, you need to recompile the java code, which is not conducive to maintenance.

This is the seventh article in the spring-boot-route series. The articles in this series are relatively simple. The main purpose is to help students who are new to Spring Boot have a systematic understanding. This article has been included in my github , welcome friends star!

githubhttps://github.com/binzh303/spring-boot-route

Pay attention, don't get lost

If you feel good essays, welcome attention , thumbs up , collection , your support is my creative power, thank you.

If there is a problem with the writing of the article, please don't be stingy. Please leave a message and point it out. I will check and modify it in time.

If you want to know me more deeply, you can search for " Java Journey " on WeChat to follow. Reply " 1024 " to get learning videos and exquisite e-books. Push technical articles on time at 7:30 every day, so that you are not alone on your way to work, and there are monthly book delivery activities to help you improve your hard power!

Guess you like

Origin blog.51cto.com/14820531/2540264