SpringBoot integrates MyBatis (pure annotation version)

Prepare

The content of this article mainly explains how SpringBoot integrates MyBatis with pure annotations. After all, the advantage of SpringBoot is that the amount of configuration is reduced, and it is not SpringBoot's style to write complicated configuration files. Therefore, this article abandons configuration files and fully embraces annotations.

Before the start of this article, the default reader has built the SpringBoot basic framework and created a test database; the framework directory structure and database test table required for this article are as follows:

Project directory structure:
initial structure

Test database:

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
  `password` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
  `addtime` datetime DEFAULT NULL,
  `updatetime` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ----------------------------
-- Records of user
-- ----------------------------
BEGIN;
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

Annotation reference table, here will explain the annotations that will appear later, so as to facilitate understanding of its functions in subsequent use:

@ResponseBody: Indicates that the return result of this method is directly written into the HTTP response body, which is generally used when obtaining data asynchronously, and is used to build RESTful APIs. After using @RequestMapping, the return value is usually parsed as a jump path. After adding @responsebody, the return result will not be parsed as a jump path, but written directly into the HTTP response body.

@Controller: It is used to define the controller class. In the spring project, the controller is responsible for forwarding the URL request sent by the user to the corresponding service interface (service layer). Generally, this annotation is in the class, and usually the method needs to cooperate with the annotation @RequestMapping .

@RestController: A collection of @ResponseBody and @Controller for annotating control layer components.

@Autowired: Automatically import dependent beans

@Mapper: Generally used to modify the components of the dao layer (Mapper layer)

@Service: Generally used to modify components of the service layer

@Repository: Using the @Repository annotation can ensure that DAO or repositories provide exception translation. The DAO or repositories classes decorated with this annotation will be discovered and configured by ComponentScan, and there is no need to provide XML configuration items for them.

@RequestMapping: Provides routing information and is responsible for mapping URLs to specific functions in the Controller. According to different needs and scenarios, @GetMapping, @PostMapping, @DeleteMapping and @PutMapping can be used instead

@RequestBody: @RequestBody is mainly used to receive the data in the json string passed from the front end to the backend (data in the request body); and the most commonly used request body to pass parameters is undoubtedly the POST request, so use @RequestBody When receiving data, generally use the POST method to submit

The knowledge here briefly introduces the meaning and literacy. Please try to study systematically and understand in depth, and master the usage methods and precautions of each common annotation. Some other annotations that do not appear here will be briefly described where they are used.

add dependencies

Add dependencies to the project POM file. Here you need to add several commonly used dependencies, as follows:

<!-- spring-boot-starter-web依赖启动器的主要作用是提供Web开发场景所需的底层所有依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis依赖、mysql驱动 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

configuration file

Next, configure application.yml to configure the data source and MyBatis separately to make it take effect:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/hexo_demo
    username: root
    password: AsdZq123..
    driver-class-name: com.mysql.cj.jdbc.Driver

# Java结果集对象中自动转换成驼峰命名参数
mybatis:
  configuration:
    map-underscore-to-camel-case: true

# 访问端口
server:
  port: 8789

Among them, the map-underscore-to-camel-case configuration is to map database fields and entity object attributes, and the table name or field name in the form of aa_bb in the database table can be automatically mapped to the form of aaBb.

Code

First, you need to create several packages in src, which are used to store Dao, Service, Entity (entity class) and Controller:
create package

  1. Entity class

First create the entity class User in Entity to map the user table in the mysql database:

import java.sql.Timestamp;

public class User{
    
    
    Integer id;
    String username;
    String password;
    Timestamp addtime;
    Timestamp updatetime;
    //...此处省略Getter和Setter方法,若使用lombok在类定义上方添加@Data注解即可,不知道具体内容可以先学习Lombok
}
  1. Mapper

Define the Mapper, create the UserMapper interface in the dao package, and define the database query. Here, first implement the basic operations of CRUD:

import com.javafeng.hexo.entity.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
public interface UserMapper{
    
    
@Select(value = "SELECT * FROM USER")
    List<User> list();

    @Insert(value = "INSERT INTO USER (USERNAME,PASSWORD,ADDTIME,UPDATETIME) VALUES ('${user.username}','${user.password}','${user.addtime}','${user.updatetime}')")
    Integer add(@Param(value = "user") User user);

    //此处先不做非空判断,后续需要可自行添加
    @Update(value = "UPDATE USER SET USERNAME='${user.username}' , PASSWORD='${user.password}' , ADDTIME='${user.addtime}' , UPDATETIME='${user.updatetime}' WHERE ID=${user.id}")
    Integer update(@Param(value = "user") User user);

    @Delete(value = "DELETE FROM USER WHERE ID = #{id}")
    Integer delete(@Param(value = "id")Integer id);
}

Because it is a pure annotation, you need to use the @Mapper annotation and @Repository annotation to register this class as a Mapper class to facilitate Spring recognition, and there is no need to configure the Mapper mapping xml file, just use the annotation to declare the query Sql.

  • The @Mapper annotation is an annotation of MyBatis, which is used to indicate that this is a Mapper, and the corresponding xxxMapper.xml is to implement this Mapper. Then use the @Autowired annotation or @Resource reference in the server layer. It can be omitted, and the configuration of the Mapper scanning base package needs to be added to the startup class:
@MapperScan(value = {
    
    "com.javafeng.hexo.mapper"})
  • @Insert annotation, @Update, @Select, @Delete declare the statement to be executed by the method.

  • The @Param annotation is used to give a name to the mapper method parameters. If not added, the parameters will be named according to their sequential positions.

The above explanations are for personal understanding only. For detailed meaning, usage, precautions and adverse reactions, please go out and turn left to Baidu Google. Thank you.

  1. Service

To write the Service interface and specific implementation class, first create a new impl implementation class subpackage in the service package, then add the UserService class in the service package, and write the query service:

import com.javafeng.hexo.entity.User;
import java.util.List;

public interface UserService {
    
    
    List<User> list();
    Integer add(User user);
    Integer update(User user);
    List<User> delete(Integer id);
}

Create the implementation class UserServiceImpl in the impl implementation class subpackage to implement the UserService interface:

import com.javafeng.hexo.dao.UserMapper;
import com.javafeng.hexo.entity.User;
import com.javafeng.hexo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    
    
    @Autowired
    UserMapper userMapper;

    @Override
    public List<User> list() {
    
    
        return userMapper.list();
    }

    @Override
    public Integer add(User user) {
    
    
        return userMapper.add(user);
    }

    @Override
    public Integer update(User user) {
    
    
        return userMapper.update(user);
    }

    @Override
    public List<User> delete(Integer id) {
    
    
        return userMapper.delete(id);
    }
}

It should be noted that what really realizes the function of Service is that the implementation class UserServiceImpl is not the UserService interface, so the @Service annotation should be added above the implementation class.

  1. Controller

Finally, there is the Controller. In the controller package, create the UserController class to handle user requests and other operations:

import com.javafeng.hexo.entity.User;
import com.javafeng.hexo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/mybatisdemo") //此Controller中所有api前缀路径为/mybatisdemo
public class UserController {
    
    
    @Autowired
    UserService userService;

    @GetMapping("/list")
    public List<User> getUserList(){
    
    
        return userService.list();
    }

    @PostMapping("/add")
    public boolean addUser(@RequestBody User user){
    
    
        Integer addCount = userService.add(user);
        if (addCount > 0){
    
    
            return true;
        }
        return false;
    }

    @PostMapping("/update")
    public boolean updateUser(@RequestBody User user){
    
    
        Integer addCount = userService.update(user);
        if (addCount > 0){
    
    
            return true;
        }
        return false;
    }

    @GetMapping("/delete")
    public boolean delUser(Integer id){
    
    
        Integer addCount = userService.delete(id);
        if (addCount > 0){
    
    
            return true;
        }
        return false;
    }
}

Because this article does not involve any web interface, all Controller methods are presented in the form of restful api, so they are directly decorated with the @RestController annotation; the next step defines four APIs for CRUD, and then run the project and use the interface to debug Tool to test interface usability.

Final directory structure:
final directory structure

After running successfully, the default port is 8080 (you can configure it yourself in application.yml, 8080 is already occupied here, so I changed it to 8789, and you can configure it according to your own port), and the access paths of the four interfaces are:

interface access path request type
Add user http://127.0.0.1:8789/mybatisdemo/add post
modify user http://127.0.0.1:8789/mybatisdemo/update post
delete users http://127.0.0.1:8789/mybatisdemo/delete get
Query users http://127.0.0.1:8789/mybatisdemo/list get

Here I use an interface debugging plug-in of Chrome browser. The specific test results are as follows:
insert image description here
insert image description here
insert image description here
insert image description here

Summarize

In fact, the content of SpringBoot integration is very simple. The Starter encapsulated by SpringBoot has done a lot of work, mainly to understand the structure and mechanism of SpringBoot and master the use of annotations.

Guess you like

Origin blog.csdn.net/u012751272/article/details/124241797