This article introduces a SpringBoot integration Mybatis-Plus, and provides a small Demo for your reference.

It has been a long time since I wrote an article. Recently, I just finished dealing with something at home and took the opportunity to rest for a while. I just returned to the company to have a look at the code cloud, and found that the person on the cover of the code cloud is the person in charge of The Mybatis-Plus team.

It just occurred to me that someone told me before why there is no SpringBoot integration of MyBtis-Plus, it has been a long time, just remember, this time to make a integration Demo.

So let’s start a new project. Add Mybatis dependencies to the poM file. The complete POM is as follows:

<? xml version="1.0" encoding="UTF-8"? > <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> < modelVersion > 4.0.0 < / modelVersion > < groupId > com. Dalaoyang < / groupId > < artifactId > springboot_mybatisplus < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > < packaging > jar < / packaging > < name > springboot_mybatisplus < / name > <description>springboot_mybatisplus</description> <parent> <groupId>org.springframework.boot</groupId> The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 1.5.9. RELEASE < / version > < relativePath / > <! -- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> < project. Reporting. OutputEncoding > utf-8 < / project. Reporting. OutputEncoding > < Java version > 1.8 < / Java version > </properties> <dependencies> <dependency> <groupId>com.baomidou</groupId> < artifactId > mybatisplus - spring - the boot - starter < / artifactId > < version > 1.0.5 < / version > < / dependency > < the dependency > </groupId> </groupId> </groupId> </artifactId> mybatis-plus</artifactId> </version> </version> </dependency> <dependency> < the groupId > org. Mybatis. Spring. The boot < / groupId > < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 1.3.1 < / version >  </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId>  <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

Copy the code

The configuration file configures the database configuration and the corresponding Mybatis-Plus entity information as follows:

# # the port number
server.port=8888

## Database url
spring.datasource.url=jdbc:mysql://localhost:3306/test? characterEncoding=utf8&useSSL=false
## Database user name
spring.datasource.username=root
## Database password
spring.datasource.password=root
## Database driver
spring.datasource.driver-class-name=com.mysql.jdbc.Driver


## Log level
logging.level.com.dalaoyang.dao.UserMapper=debug
## myBatis -plus mapper XML file address
mybatis-plus.mapper-locations=classpath*:mapper/*Mapper.xml
##mybatis-plus type-aliases
mybatis-plus.type-aliases-package=com.dalaoyang.entity
Copy the code

The entity class User code is as follows:

package com.dalaoyang.entity;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.entity
 * @email [email protected]
 * @date 2018/7/20
 */
public class User {
    private int id;
    private String user_name;
    private String user_password;

    public User() {
    }

    public User(String user_name, String user_password) {
        this.user_name = user_name;
        this.user_password = user_password;
    }

    public User(int id, String user_name, String user_password) {
        this.id = id;
        this.user_name = user_name;
        this.user_password = user_password;
    }

    public int getId() {
        return id;
    }

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

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public String getUser_password() {
        return user_password;
    }

    public void setUser_password(String user_password) { this.user_password = user_password; }}Copy the code

MybatisPlus (MybatisPlus) {MybatisPlus (MybatisPlus) {MybatisPlus (MybatisPlus);

package com.dalaoyang.config;

import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.config
 * @email [email protected]
 * @date 2018/7/20
 */
@Configuration
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor(){ PaginationInterceptor page = new PaginationInterceptor(); Page. SetDialectType ()"mysql");
        returnpage; }}Copy the code

MybatisPlus (BaseMapper); UserMapper (BaseMapper);

package com.dalaoyang.dao;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.dalaoyang.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.dao
 * @email [email protected]
 * @date 2018/7/20
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {
    List<User> getUserList();

}
Copy the code

Create a new userMapper. XML and write getUserList (SQL) as follows:

<? xml version="1.0" encoding="UTF-8"? > <! DOCTYPE mapper PUBLIC"- / / mybatis.org//DTD Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.dalaoyang.dao.UserMapper">
    <resultMap id="user" type="com.dalaoyang.entity.User"/>
    <parameterMap id="user" type="com.dalaoyang.entity.User"/>

    <select id="getUserList" resultMap="user">
        SELECT  * FROM USER
    </select>
</mapper>
Copy the code

Finally, as usual, create a new Controller to test. The complete code looks like this:

package com.dalaoyang.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dalaoyang.dao.UserMapper;
import com.dalaoyang.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.controller
 * @email [email protected]
 * @date 2018/7/20
 */
@RestController
public class UserController {

    @Autowired
    private UserMapper userDao;

    //http://localhost:8888/getUserList
    @GetMapping("getUserList")
    public List<User> getUserList() {returnuserDao.getUserList(); } //http://localhost:8888/getUserListByName? UserName =xiaoli //"getUserListByName")
    public List<User> getUserListByName(String userName)
    {
        Map map = new HashMap();
        map.put("user_name", userName);
        returnuserDao.selectByMap(map); } //http://localhost:8888/saveUser? UserName =xiaoli&userPassword=111"saveUser")
    public String saveUser(String userName,String userPassword)
    {
        User user = new User(userName,userPassword);
        Integer index = userDao.insert(user);
        if(index>0){
            return "User added successfully.";
        }else{
            return "Failed to add user."; } } //http://localhost:8888/updateUser? Id =5 &username =xiaoli&userPassword=111"updateUser")
    public String updateUser(Integer id,String userName,String userPassword)
    {
        User user = new User(id,userName,userPassword);
        Integer index = userDao.updateById(user);
        if(index>0){
            return "User modified successfully, affecting row number"+index+"Line.";
        }else{
            return "Failed to modify user, affecting row number"+index+"Line."; } } //http://localhost:8888/getUserById? UserId =1 userId=1"getUserById")
    public User getUserById(Integer userId)
    {
        returnuserDao.selectById(userId); } //http://localhost:8888/getUserListByPage? PageNumber =1&pageSize=2"getUserListByPage")
    public List<User> getUserListByPage(Integer pageNumber,Integer pageSize)
    {
        Page<User> page =new Page<>(pageNumber,pageSize);
        EntityWrapper<User> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("user_name"."xiaoli");
        returnuserDao.selectPage(page,entityWrapper); }}Copy the code

Here’s an explanation of the above code, which includes the following methods:

1. GetUserList: this is a normal Mybatis query method, without using Mybatis-Plus, not too much explanation here.

2. GetUserListByName: a conditional query to query the user list according to the name. SelectByMap is used here.

3. SaveUser: save the user. Insert: pass an entity object and return an Integer as the number of rows affected.

4. UpdateUser: Modify the user. This is the updateByIdt method, need to pass an entity object, return the Integer value as the number of rows affected. 5. GetUserById: Queries the entity object based on the Id. You need to send the user Id.

GetUserListByPage: A conditional paging query by using the selectPage method. The method requires a Page object, Page, and a condition object, EntityWrapper. Page puts the Page number and the number of pages per Page, EntityWrapper uses eq method to put the corresponding field name and the corresponding query value.

Here only illustrates several methods, including methods, there are many more Mybatis – Plus use please see the official document: baomidou. Oschina. IO/Mybatis – plu…

Source download: Old Yang code cloud

Personal website: www.dalaoyang.cn

Follow the author’s official account