This is the sixth day of my participation in the First Challenge 2022. For details: First Challenge 2022.

1. The JdbcTemplate overview

After the previous articles, we have almost finished explaining some of the operations in the front controller in SpringBoot, and experienced the convenience SpringBoot brings to using the framework. For all the cases in the previous articles, a total of one Web-starter was introduced, with very little configuration. Starting today, we’ll take a look at how SpringBoot can persist data.

There are frameworks for persistence in general, For example, some original JDBC, old brand strength JPA(Hibernate), and now use the comparison or Mybatis and MybatisPlus, and SpringBoot we are to choose the persistence layer framework to use, and then use SpringBoot for integration. The integration step is greatly simplified by SpringBoot’s automated configuration capabilities.

Today we will start with a simple JdbcTemplate, which is a JdbcTemplate framework that Spring encapsulates based on Jdbc. It is dedicated to lightweight and easy operation of databases. His operation is very simple, but not as comprehensive as Mybatis and JPA, but stronger than native JDBC, to tell the truth, the actual use is relatively less.

2. Integration steps

2.1 Importing Dependencies

<! -- jdbcTemplate -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
 
<! MySQL > select * from 'MySQL';
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
Copy the code

2.2 Configuring database Connections

In the SpringBoot configuration file, configure the connection to the database, which is required for all operations on the database. Mainly includes the use of the driver class, database connection address, user name password and so on.

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot_learning
    username: root
    password: root
Copy the code

I created a database called Springboot_learning in my local database for testing.

Then we create a user table.

CREATE TABLE `springboot_learning`.`t_user`  (
  `id` int(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `name` varchar(40) NULL COMMENT 'name',
  `age` int(20) NULL COMMENT 'age',
  `address` varchar(100) NULL COMMENT 'address',
  `create_time` datetime(0) NULL COMMENT 'Creation time',
  `update_time` datetime(0) NULL COMMENT 'Update Time'.PRIMARY KEY (`id`)
);
Copy the code

2.3 Develop entities and DAOs

Create an Entity folder, and then create an entity class User

@Data
public class User {

    private Integer id;

    private String name;

    private Integer age;

    private String address;

    private Date createTime;

    private Date updateTime;

}
Copy the code

The development of UserDao includes commonly used add, delete, change and check interface

UserDao interface

/ * * *@interface: UserDao
 * @description:
 * @author: sh.Liu
 * @date: scatter * / 2022-01-14
public interface UserDao {
    /** * query * by id@param id
     * @return* /
    User getUserById(Integer id);

    /** * Query all users *@return* /
    List<User> listUser(a);

    /** * Save user *@param user
     * @return* /
    int save(User user);

    /** * Update user *@param id
     * @param user
     * @return* /
    int update(Integer id, User user);

    /** * Delete user *@param id
     * @return* /
    int delete(Integer id);


}
Copy the code

UserDaoImpl implementation: Injects the JdbcTemplate interface into the class, which spring provides for us to manipulate the core object of the database. The @repository annotation also identifies the class as being used to handle database operations. Can be scanned by Spring.

UserDaoImpl code is as follows:

package com.lsqingfeng.springboot.dao.jdbcTemplate.impl;

import com.lsqingfeng.springboot.dao.jdbcTemplate.UserDao;
import com.lsqingfeng.springboot.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

/ * * *@className: UserDaoImpl
 * @description:
 * @author: sh.Liu
 * @date: the ephod 2022-01-14 * /
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public User getUserById(Integer id) {
        User user  = jdbcTemplate.queryForObject("select * from t_user where id = ?".new BeanPropertyRowMapper<User>(User.class), id);
        return user;
    }

    @Override
    public List<User> listUser(a) {
        List<User> users = jdbcTemplate.query("select * from t_user".new BeanPropertyRowMapper<User>(User.class));
        return users;
    }

    @Override
    public int save(User user) {
        return jdbcTemplate.update("insert into t_user(name, age, address, create_time, update_time) values(? ,? ,? ,? ,?) ",
                user.getName(),user.getAge(), user.getAddress(),new Date(),new Date());
    }

    @Override
    public int update(Integer id, User user) {
        return jdbcTemplate.update("UPDATE t_user SET name = ? , age = ? ,address = ? ,update_time = ? WHERE id=?",
                user.getName(), user.getAge(), user.getAddress(), new Date(), id);
    }

    @Override
    public int delete(Integer id) {
        return jdbcTemplate.update("DELETE from tb_user where id = ? ",id); }}Copy the code

We package a Service layer, and currently the mainstream project interface is also controller-service-DAO logic.

2.4 Service Layer development

Create a service package with a UserService interface. The service layer is generally used to process business logic, and the code with transaction is generally placed in this layer. It is generally divided according to business modules. The name can not be developed with entity name or table name, and it is generally the encapsulation of multiple Dao layer operations. Understanding the Service layer thoroughly can also require more project experience. This is mainly for demonstration purposes, and there is no particularly complicated business, so we’ll just call it UserService. Take all the methods from the Dao layer.

UserService

/ * * *@interface: UserService
 * @description:
 * @author: sh.Liu
 * @date: the 2022-01-17 13:56 * /
public interface UserService {
    /** * query * by id@param id
     * @return* /
    User getUserById(Integer id);

    /** * Query all users *@return* /
    List<User> listUser(a);

    /** * Save user *@param user
     * @return* /
    int save(User user);

    /** * Update user *@param id
     * @param user
     * @return* /
    int update(Integer id, User user);

    /** * Delete user *@param id
     * @return* /
    int delete(Integer id);


}
Copy the code

In the implementation class, Dao is directly injected and the same function is achieved by calling Dao.

/ * * *@className: UserServiceImpl
 * @description:
 * @author: sh.Liu
 * @date: the 2022-01-17 13:56 * /
@Service
public class UserServiceImpl implements UserService {

    // This is constructor injection, equivalent to @autowired
    private final UserDao userDao;

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public User getUserById(Integer id) {
        return userDao.getUserById(id);
    }

    @Override
    public List<User> listUser(a) {
        return userDao.listUser();
    }

    @Override
    public int save(User user) {
        return userDao.save(user);
    }

    @Override
    public int update(Integer id, User user) {
        return userDao.update(id, user);
    }

    @Override
    public int delete(Integer id) {
        returnuserDao.delete(id); }}Copy the code

2.5 Develop Controller for testing

Now that the Dao and Service are ready, let’s develop a Controller to test to see if we can successfully manipulate the database.

package com.lsqingfeng.springboot.controller;

import com.lsqingfeng.springboot.base.Result;
import com.lsqingfeng.springboot.entity.User;
import com.lsqingfeng.springboot.exception.BizException;
import com.lsqingfeng.springboot.service.UserService;
import org.springframework.web.bind.annotation.*;

/ * * *@className: JdbcController
 * @description:
 * @author: sh.Liu
 * @date: the 2022-01-17 13:58 * /
@RestController
@RequestMapping("jdbc")
public class JdbcController {

    /** * this is constructor injection, equivalent to@autowired* /
    private final UserService userService;

    public JdbcController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("save")
    public Result save(@RequestBody User user){
        userService.save(user);
        return Result.success();
    }

    @PostMapping("update")
    public Result update(@RequestBody User user){
        if (user.getId() == null) {
            throw new BizException("Update operation ID cannot be empty");
        }
        userService.update(user.getId(), user);
        return Result.success();
    }

    @GetMapping("get/{id}")
    public Result getById(@PathVariable Integer id){
        return Result.success(userService.getUserById(id));
    }

    @GetMapping("list")
    public Result list(a){
        return Result.success(userService.listUser());
    }

    @GetMapping("delete/{id}")
    public Result delete(@PathVariable Integer id){
        userService.delete(id);
        returnResult.success(); }}Copy the code

We used postMan for testing. Don’t forget to pass the header, because our interceptor requires it

Return success, view data in database:

The data is saved successfully.

Let’s try the getById method again

The other methods are not demonstrated.

3. Summary

The JdbcTemplate class is used to configure the connection between the JdbcTemplate database and the JdbcTemplate class. The JdbcTemplate class already encapsulates most of the operations on the database. Simple is simple, but this framework in the enterprise project application is less, generally used for the operation of the database is not high requirements of the project, because he is the SIMPLE ENCAPSULATION of JDBC, all SQL is written into the code, poor maintenance, looks more messy. Later we will continue to introduce the usage of Mybatis and JPA, the mainstream DAO layer framework. I hope this article has been helpful.

GitCode: gitcode.net/lsqingfeng/…

All articles will be first updated in the wechat public account, welcome to pay attention to: a wisp of 82 years of wind