Introduction to SpringBoot

One, foreword

  • Mybatis: Data Persistence framework
  • Mybatis-Plus: Enhanced Mybatis, it encapsulates the basic add, delete, change and check operations, so that we do not need to write a lot of repeated code, greatly liberating productivity!

2. Create a project

Delete the test directory under SRC

Third, directory structure

Four, pom. XML

Modify pom.xml as follows


      
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2. RELEASE</version>
        <relativePath/> <! -- lookup parent from repository -->
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.llh</groupId>
    <artifactId>spring-boot-demo</artifactId>
    <version>1.0.0</version>
    <name>spring-boot-demo</name>
    <description>springboot project description</description>

    <properties>
        <mybatis-spring-boot.version>2.1.4</mybatis-spring-boot.version>
        <mybatis-plus.version>3.4.2</mybatis-plus.version>
    </properties>

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

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

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

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis-spring-boot.version}</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>

    </dependencies>

</project>

Copy the code

Description: In spring-boot-starter-parent help us to do the SpringBoot dependency package version number management, Therefore, some dependency packages do not need to be written by ourselves, but for example, mybatis-plus-boot-starter is not related to spring-boot. There is no version number management in parent, so it needs to be written manually.

SQL and Application.properties

5.1 Importing SQL Statements

CREATE TABLE `user_info` (
	`id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'user id',
	`username` VARCHAR(20) NOT NULL DEFAULT ' ' COMMENT 'Username' COLLATE 'utf8mb4_general_ci',
	`password` VARCHAR(100) NOT NULL DEFAULT ' ' COMMENT 'password' COLLATE 'utf8mb4_general_ci',
	`create_time` DATETIME NOT NULL COMMENT 'Creation time'.PRIMARY KEY (`id`) USING BTREE
);
Copy the code

Create a database, and then run the above SQL statement, generate user table, mainly on the following four fields

  • Id The primary key is automatically added to the user ID
  • The username username
  • “Password,” password
  • Create_time Creation time

5.2 Modifying the application.properties configuration file

Name =spring-boot-demo server.port=8888 spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shang hai&useSSL=false spring.datasource.username=root spring.datasource.password=0320 Spring.datasource. Driver-class-name = com.mysql.cj.jdbc.driver # mybatis mybatis.mapper-locations=classpath:mapper/*Mapper.xmlCopy the code

Description:

  • Database address localhost:3306/demo. Demo is the database name
  • Database user name spring. The datasource. The username
  • Database password spring. The datasource. The password
  • Mybatis. Mapper-locations Configures the scan CODE XML file

Six, logical code

SpringBootDemoApplication class

package com.llh.springbootdemo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/ * * *@author llh
 */
@SpringBootApplication
@MapperScan(value = "com.llh.springbootdemo.mapper")
public class SpringBootDemoApplication {

    public static void main(String[] args) { SpringApplication.run(SpringBootDemoApplication.class, args); }}Copy the code

Start class plus

@MapperScan(value = "com.llh.springbootdemo.mapper")
Copy the code

The function is to scan to mapper inside the class, pay attention to the path and the actual path in the project


The UserInfo class

package com.llh.springbootdemo.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;

import java.time.LocalDateTime;

/ * * *@author llh
 */
public class UserInfo {
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    private String username;
    private String password;
    private LocalDateTime createTime;

    public Long getId(a) {
        return id;
    }

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

    public String getUsername(a) {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword(a) {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public LocalDateTime getCreateTime(a) {
        return createTime;
    }

    public void setCreateTime(LocalDateTime createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString(a) {
        return "UserInfo{" +
                "id=" + id +
                ", username='" + username + '\' ' +
                ", password='" + password + '\' ' +
                ", createTime=" + createTime +
                '} '; }}Copy the code

Mybatis: create_time -> createTime; Mybatis: create_time -> createTime


UserInfoMapper class

package com.llh.springbootdemo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.llh.springbootdemo.entity.UserInfo;

/ * * *@author llh
 */
public interface UserInfoMapper extends BaseMapper<UserInfo> {}Copy the code

BaseMapper class encapsulates the dao layer basic add, delete, change and check operations


mapper/UserInfoMapper.xml


      
<! DOCTYPEmapper PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.llh.springbootdemo.mapper.UserInfoMapper">

</mapper>
Copy the code

Note: The namespace is the same as the UserInfoMapper path


UserInfoService class

package com.llh.springbootdemo.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.llh.springbootdemo.entity.UserInfo;

/ * * *@author llh
 */
public interface UserInfoService extends IService<UserInfo> {}Copy the code

Here IService encapsulates the service layer of the basic add, delete, change, check


UserInfoServiceImpl class

package com.llh.springbootdemo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.llh.springbootdemo.entity.UserInfo;
import com.llh.springbootdemo.mapper.UserInfoMapper;
import com.llh.springbootdemo.service.UserInfoService;
import org.springframework.stereotype.Service;

/ * * *@author llh
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper.UserInfo> implements UserInfoService {}Copy the code

UserInfoController class

package com.llh.springbootdemo.controller;

import com.llh.springbootdemo.entity.UserInfo;
import com.llh.springbootdemo.service.UserInfoService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/ * * *@author llh
 */
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {
    @Resource
    private UserInfoService userInfoService;

    @PostMapping("/add")
    public Boolean add(@RequestBody UserInfo userInfo) {
        userInfo.setCreateTime(LocalDateTime.now());
        return userInfoService.save(userInfo);
    }

    @GetMapping("/delete/{id}")
    public Boolean delete(@PathVariable Long id) {
        return userInfoService.removeById(id);
    }

    @PostMapping("/update")
    public Boolean update(@RequestBody UserInfo userInfo) {
        return userInfoService.updateById(userInfo);
    }

    @GetMapping("/get/{id}")
    public UserInfo get(@PathVariable Long id) {
        return userInfoService.getById(id);
    }

    @GetMapping("/list")
    public List<UserInfo> list(a) {
        returnuserInfoService.list(); }}Copy the code

Description:

  • Add, delete, change and check interface, basically do not need to write THEIR own SQL, directly call Mybatis-Plus encapsulated interface.

Seven, conclusion

Using Mybatis-Plus is not very easy, hey hey.

Mybatis-Plus add, delete, change, check method interface is as follows:

Mybatis is a semi-configuration data persistence framework. JPA directly encapsulates all SQL operations. Compared with JPA, Mybatis is more flexible and can customize SQL. At the same time, Mybatis-Plus also for you to encapsulate the common add, delete, change and check operations, so that you can customize SQL in special cases, and avoid writing a large number of repeated add, delete, change and check.

Of course, Mybatis-Plus also has many more interesting things, such as auto-filling field values, such as creation time, update time fields can be directly assigned through the unified interception, no need to manually set. Other examples include multi-tenant, logical deletion, and so on. We’ll talk about that later.

Synchronize wechat official account: Little Tiger’s technology blog