Springboot quickly build mybatisplus project + problem summary

Compared with the commonly used mybatis, mybatisPlus can help us focus more on business development and reduce the coding of sql files. Let's use SpringBoot
+ mybatisPlus build a project.

1. Summary of problems encountered during the construction process

(1) Start-up error report

Add dependency

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.3.1.tmp</version>
</dependency>

Because of the reference relationship, it is mandatory to upgrade the mybatis-spring-boot-starter version number to 2.0.0 or higher.

<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>2.0.1</version>
</dependency>
(2) Service can have a method of operating the database by inheriting IService<T>

Ways to realize the query 1,

userService.getOne(Wrappers.<User>lambdaQuery().eq(false, User :: getId, 3L).orderByDesc(User::getId).last("limit 1"));

Ways to realize the query 2,

QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "Save1").or().eq("phone_number", "17300000001").orderByDesc("id");

(3) There are many pitfalls in the mybatisPlus method. For example, the getOne method returns a single model, but sql does not add limit 1

So it needs to be spelled in the back.last("limit 1"));

Therefore, there may be many problems in use, it is recommended to look at the method implementation of IService first

## spring-boot-demo-mybatis-plus

#pom
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.juejueguai</groupId>
        <artifactId>spring-boot-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-boot-demo-mybatis-plus</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-demo-mybatis-plus</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

#yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/spring_boot_test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
    type: com.zaxxer.hikari.HikariDataSource
    initialization-mode: always
    continue-on-error: true
    hikari:
      minimum-idle: 5
      connection-test-query: SELECT 1 FROM DUAL
      maximum-pool-size: 20
      auto-commit: true
      idle-timeout: 30000
      pool-name: SpringBootDemoHikariCP
      max-lifetime: 60000
      connection-timeout: 30000
logging:
  level:
    com.juejueguai: debug
    com..juejueguai.springbootdemomybatisplus.mapper: trace
mybatis-plus:
  mapper-locations: classpath:mappers/*.xml
  #Entity scanning, multiple packages separated by commas or semicolons
  typeAliasesPackage: com.juejueguai.springbootdemomybatisplus.entity
  global-config:
    # Database related configuration
    db-config:
      #Primary key type AUTO: "Database ID self-increment", INPUT: "User input ID", ID_WORKER: "Globally unique ID (number type unique ID)", UUID: "Globally unique ID UUID";
      id-type: auto
      #Field strategy IGNORED: "ignore judgment", NOT_NULL: "non-NULL judgment"), NOT_EMPTY: "non-null judgment"
      field-strategy: not_empty
      #Hump underline conversion
      table-underline: true
      #Whether to enable capital naming, not enabled by default
      #capital-mode: true
      #Logical delete configuration
      #logic-delete-value: 1
      #logic-not-delete-value: 0
      db-type: mysql
    #Refresh mapper debugging artifact
    refresh: true
  #Primary arrangement
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: true
server:
  port: 9004

# sql file
/*
Navicat MySQL Data Transfer

Source Server: local database
Source Server Version : 50549
Source Host           : localhost:3306
Source Database       : spring_boot_test

Target Server Type    : MYSQL
Target Server Version : 50549
File Encoding         : 65001

Date: 2020-07-17 16:16:48
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for orm_role
-- ----------------------------
DROP TABLE IF EXISTS `orm_role`;
CREATE TABLE `orm_role` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(32) NOT NULL COMMENT'role name',
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='Spring Boot Demo Orm series example table';

-- ----------------------------
-- Records of orm_role
-- ----------------------------
INSERT INTO `orm_role` VALUES ('2','ordinary user');
INSERT INTO `orm_role` VALUES ('1','Administrator');


/*
Navicat MySQL Data Transfer

Source Server: local database
Source Server Version : 50549
Source Host           : localhost:3306
Source Database       : spring_boot_test

Target Server Type    : MYSQL
Target Server Version : 50549
File Encoding         : 65001

Date: 2020-07-17 16:17:23
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for orm_user
-- ----------------------------
DROP TABLE IF EXISTS `orm_user`;
CREATE TABLE `orm_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(32) NOT NULL COMMENT'Username',
  `password` varchar(32) NOT NULL COMMENT'encrypted password',
  `salt` varchar(32) NOT NULL COMMENT'Salt used for encryption',
  `email` varchar(32) NOT NULL COMMENT'mailbox',
  `phone_number` varchar(15) NOT NULL COMMENT'phone number',
  `status` int(2) NOT NULL DEFAULT '1' COMMENT'status, -1: logical deletion, 0: disable, 1: enable',
  `create_time` datetime DEFAULT NULL COMMENT'create time',
  `last_login_time` datetime DEFAULT NULL COMMENT'Last login time',
  `last_update_time` datetime DEFAULT NULL COMMENT'Last update time',
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`),
  UNIQUE KEY `email` (`email`),
  UNIQUE KEY `phone_number` (`phone_number`)
) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8 COMMENT='Spring Boot Demo Orm series example table';

-- ----------------------------
-- Records of orm_user
-- ----------------------------
INSERT INTO `orm_user` VALUES ('2', 'user_2', '6c6bf02c8d5d3d128f34b1700cb1e32c', 'fcbdd0e8a9404a5585ea4e01d0e4d7a0', '[email protected]', '17300000002', '1', null, null, null);
INSERT INTO `orm_user` VALUES ('3','MybatisPlus modify name', '123456456', '456','[email protected]', '17300000003', '1', '2020-07-17 14:52 :15', '2020-07-17 14:52:15', '2020-07-17 15:05:46');
INSERT INTO `orm_user` VALUES ('4', 'testSave4', '123456456', '456', '[email protected]', '17300000004', '1', '2020-07-17 14:52:51', '2020-07-17 14:52:51', '2020-07-17 14:52:51');
INSERT INTO `orm_user` VALUES ('5', 'testSave5', '123456456', '456', '[email protected]', '17300000005', '1', '2020-07-17 14:52:51', '2020-07-17 14:52:51', '2020-07-17 14:52:51');
INSERT INTO `orm_user` VALUES ('6', 'testSave6', '123456456', '456', '[email protected]', '17300000006', '1', '2020-07-17 14:52:51', '2020-07-17 14:52:51', '2020-07-17 14:52:51');
INSERT INTO `orm_user` VALUES ('7', 'testSave7', '123456456', '456', '[email protected]', '17300000007', '1', '2020-07-17 14:52:51', '2020-07-17 14:52:51', '2020-07-17 14:52:51');
INSERT INTO `orm_user` VALUES ('8', 'testSave8', '123456456', '456', '[email protected]', '17300000008', '1', '2020-07-17 14:52:51', '2020-07-17 14:52:51', '2020-07-17 14:52:51');
INSERT INTO `orm_user` VALUES ('9', 'testSave9', '123456456', '456', '[email protected]', '17300000009', '1', '2020-07-17 14:52:51', '2020-07-17 14:52:51', '2020-07-17 14:52:51');
INSERT INTO `orm_user` VALUES ('10', 'testSave10', '123456456', '456', '[email protected]', '173000000010', '1', '2020-07-17 14:52:51', '2020-07-17 14:52:51', '2020-07-17 14:52:51');
INSERT INTO `orm_user` VALUES ('11', 'testSave11', '123456456', '456', '[email protected]', '173000000011', '1', '2020-07-17 14:52:51', '2020-07-17 14:52:51', '2020-07-17 14:52:51');
INSERT INTO `orm_user` VALUES ('12', 'testSave12', '123456456', '456', '[email protected]', '173000000012', '1', '2020-07-17 14:52:51', '2020-07-17 14:52:51', '2020-07-17 14:52:51');
INSERT INTO `orm_user` VALUES ('13', 'testSave13', '123456456', '456', '[email protected]', '173000000013', '1', '2020-07-17 14:52:51', '2020-07-17 14:52:51', '2020-07-17 14:52:51');
INSERT INTO `orm_user` VALUES ('24', 'testSave14', '123456456', '456', '[email protected]', '173000000014', '1', '2020-07-17 15:16:00', '2020-07-17 15:16:00', '2020-07-17 15:16:00');
INSERT INTO `orm_user` VALUES ('25', 'testSave15', '123456456', '456', '[email protected]', '173000000015', '1', '2020-07-17 15:16:00', '2020-07-17 15:16:00', '2020-07-17 15:16:00');
INSERT INTO `orm_user` VALUES ('26', 'testSave16', '123456456', '456', '[email protected]', '173000000016', '1', '2020-07-17 15:16:00', '2020-07-17 15:16:00', '2020-07-17 15:16:00');
INSERT INTO `orm_user` VALUES ('27', 'testSave17', '123456456', '456', '[email protected]', '173000000017', '1', '2020-07-17 15:16:00', '2020-07-17 15:16:00', '2020-07-17 15:16:00');
INSERT INTO `orm_user` VALUES ('28', 'testSave18', '123456456', '456', '[email protected]', '173000000018', '1', '2020-07-17 15:16:00', '2020-07-17 15:16:00', '2020-07-17 15:16:00');
INSERT INTO `orm_user` VALUES ('29', 'testSave19', '123456456', '456', '[email protected]', '173000000019', '1', '2020-07-17 15:16:00', '2020-07-17 15:16:00', '2020-07-17 15:16:00');

# config file
@ Slf4j
@Component
public class CommonFieldHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("lastUpdateTime", new Date(), metaObject);
    }
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.setFieldValByName("lastUpdateTime", new Date(), metaObject);
    }
}

@Configuration
@MapperScan(basePackages = {"com.juejueguai.springbootdemomybatisplus.mapper"})
@EnableTransactionManagement
public class MybatisPlusConfig {
    @Bean
    public PaginationInterceptor paginationInterceptor () {
        return new PaginationInterceptor();
    }
}
# entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@TableName("orm_user")
public class User implements Serializable {
    private static final long serialVersionUID = -1840831686851699943L;
    /**
     * Primary key
     */
    private Long id;
    /**
     * username
     */
    private String name;
    /**
     * Encrypted password
     */
    private String password;
    /**
     * The salt used for encryption
     */
    private String salt;
    /**
     * Email
     */
    private String email;
    /**
     * mobile phone number
     */
    private String phoneNumber;
    /**
     * Status, -1: logical deletion, 0: disable, 1: enable
     */
    private Integer status;
    /**
     * Creation time
     */
    @TableField(fill = INSERT)
    private Date createTime;
    /**
     * Last Login Time
     */
    private Date lastLoginTime;
    /**
     * Last update time
     */
    @TableField(fill = INSERT_UPDATE)
    private Date lastUpdateTime;
}

# mapper
@Component
public interface UserMapper extends BaseMapper<User> {
}
# service
public interface UserService extends IService<User> {
}

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

# test

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootDemoMybatisPlusApplicationTests {
    @Test
    public void contextLoads() {
    }
}

@ Slf4j
public class UserServiceTest extends SpringBootDemoMybatisPlusApplicationTests {
    @Autowired
    private UserService userService;
    /**
     * Test Mybatis-Plus added
     */
    @Test
    public void testSave() {
        String salt = "456";
        User testSave3 = User.builder().name("testSave").password("123456" + salt).salt(salt).email("[email protected]").phoneNumber("17300000003").status(1).lastLoginTime(new Date()).build();
        boolean save = userService.save(testSave3);
        Assert.assertTrue(save);
        log.debug("【测试id回显#testSave3.getId()】= {}", testSave3.getId());
    }
    /**
     * Test Mybatis-Plus batch addition
     */
    @Test
    public void testSaveList() {
        List<User> userList = Lists.newArrayList();
        for (int i = 14; i < 20; i++) {
            String salt = "456";
            User user = User.builder().name("testSave" + i).password("123456" + salt).salt(salt).email("testSave" + i + "@xkcoding.com").phoneNumber("1730000000" + i).status(1).lastLoginTime(new Date()).build();
            userList.add(user);
        }
        boolean batch = userService.saveBatch(userList);
        Assert.assertTrue(batch);
        List<Long> ids = userList.stream().map(User::getId).collect(Collectors.toList());
        log.debug("【userList#ids】= {}", ids);
    }
    /**
     * Test Mybatis-Plus delete
     */
    @Test
    public void testDelete() {
        boolean remove = userService.removeById(1L);
        User byId = userService.getById(1L);
        Assert.assertNull(byId);
    }
    /**
     * Test Mybatis-Plus modification
     */
    @Test
    public void testUpdate() {
        User user = userService.getById(3L);
        user.setName("MybatisPlus modify name");
        boolean b = userService.updateById(user);
        Assert.assertTrue(b);
        User update = userService.getById(3L);
        Assert.assertEquals("MybatisPlus modify name", update.getName());
        log.debug("【update】= {}", update);
    }
    /**
     * Test Mybatis-Plus to query a single
     */
    @Test
    public void testQueryOne() {
        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(false, User :: getId, 3L).orderByDesc(User::getId).last("limit 1"));
        Assert.assertNotNull(user);
        log.debug("【user】= {}", user);
    }
    /**
     * Test Mybatis-Plus to check all
     */
    @Test
    public void testQueryAll() {
        List<User> list = userService.list(new QueryWrapper<>());
        Assert.assertTrue(!CollectionUtils.isEmpty(list));
        log.debug("【list】= {}", list);
    }
    /**
     * Test Mybatis-Plus paging sort query
     */
    @Test
    public void testQueryByPageAndSort() {
        initData ();
        int count = userService.count(new QueryWrapper<>());
        Page<User> userPage = new Page<>(1, 5);
        userPage.setDesc("id");
        IPage<User> page = userService.page(userPage, new QueryWrapper<>());
        Assert.assertEquals(5, page.getSize());
        Assert.assertEquals(count, page.getTotal());
        log.debug("【page.getRecords()】= {}", page.getRecords());
    }
    /**
     * Test Mybatis-Plus custom query
     */
    @Test
    public void testQueryByCondition() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("name", "Save1").or().eq("phone_number", "17300000001").orderByDesc("id");

        userService.getOne(wrapper);
        int count = userService.count(wrapper);
        Page<User> userPage = new Page<>(1, 3);
        IPage<User> page = userService.page(userPage, wrapper);
        Assert.assertEquals(3, page.getSize());
        Assert.assertEquals(count, page.getTotal());
        log.debug("【page.getRecords()】= {}", page.getRecords());
    }
    /**
     * Initialization data
     */
    private void initData() {
        testSaveList ();
    }

}
Source code path: https://github.com/juejuedog/SpringBootDemo.git

Guess you like

Origin blog.csdn.net/A___B___C/article/details/107412292