【博客项目二】SpringBoot 2.2 集成 Mybatis-plus

springboot 2.2 集成 mybatis-plus,列出了几个集成遇到的bug及示例源码。

集成 mybatis-plus 步骤

添加maven依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
	<version>3.1.0</version>
</dependency>
<!--分页-->
<dependency>
	<groupId>com.github.pagehelper</groupId>
	<artifactId>pagehelper-spring-boot-starter</artifactId>
	<version>1.2.12</version>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>1.1.10</version>
</dependency>
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<optional>true</optional>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>

添加业务代码

User

package com.blackcat.mybatis.entity;

import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.*;

/**
 * <p> :测试用户
 * @author : blackcat
 * @date : 2020/1/18 12:58
 */
@Data
@NoArgsConstructor// 生成一个无参数的构造方法
@AllArgsConstructor// 会生成一个包含所有变量的构造方法
@TableName("TB_USER")
public class User extends Model<User> {
    @TableId(value = "USER_ID", type = IdType.AUTO)
    private Integer userId;

    @TableField("USER_NAME")
    private String userName;
}

添加UserMapper

package com.blackcat.mybatis.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.blackcat.mybatis.entity.User;

import java.util.List;

/**
 * <p> :Mapper
 * @author : blackcat
 * @date : 2020/1/18 12:57
 */
public interface UserMapper  extends BaseMapper<User> {
    /**
     * 获取用户信息
     */
    List<User> findAllUser();
}

添加IUserService

package com.blackcat.mybatis.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.blackcat.mybatis.entity.User;

/**
 * <p> :
 * @author : blackcat
 * @date : 2020/1/18 12:59
 */
public interface IUserService extends IService<User> {

    /**
     * 添加新用户
     */
    Object addUser(String userName);

    /**
     * 查询用户列表
     */
    Object findUserList(Integer pageNo, Integer pageSize);
}

添加UserServiceImpl

package com.blackcat.mybatis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blackcat.mybatis.entity.User;
import com.blackcat.mybatis.mapper.UserMapper;
import com.blackcat.mybatis.service.IUserService;
import lombok.Data;
import org.springframework.stereotype.Service;

/**
 * <p> :
 * @author : blackcat
 * @date : 2020/1/18 13:01
 */
@Service("userService")
@Data
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Object addUser(String userName) {
        User user = new User(null, userName);
        int ret = baseMapper.insert(user);
        return ret;
    }

    @Override
    public Object findUserList(Integer pageNo, Integer pageSize) {
        IPage<User> page = new Page<>(pageNo, pageSize);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("USER_ID");
        IPage<User> userIPage = baseMapper.selectPage(page, wrapper);
        return userIPage;
    }
}

添加MybatisPlusConfig

package com.blackcat.mybatis;

import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.*;
import com.github.pagehelper.PageHelper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.*;

import java.util.Properties;

/**
 * <p> :Mybatis-Plus配置类
 * @author : blackcat
 * @date : 2020/1/18 12:44
 */
@Configuration
@MapperScan("com.blackcat.mybatis.mapper")//这个注解,作用相当于下面的@Bean MapperScannerConfigurer,2者配置1份即可
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setDialectType("mysql");
        return paginationInterceptor;
    }

    /**
     * sql注入器  逻辑删除插件
     *
     * @return
     */
    @Bean
    public ISqlInjector iSqlInjector() {
        return new LogicSqlInjector();
    }

    /**
     * sql性能分析插件,输出sql语句及所需时间
     *
     * @return
     */
    @Bean
    @Profile({"dev", "test"})// 设置 dev test 环境开启
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        performanceInterceptor.setFormat(true);
        return performanceInterceptor;
    }

    /**
     * 配置mybatis的分页插件pageHelper
     * @return
     */
    @Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("offsetAsPageNum", "true");
        properties.setProperty("rowBoundsWithCount", "true");
        properties.setProperty("reasonable", "true");
        properties.setProperty("dialect", "mysql");
        pageHelper.setProperties(properties);
        return pageHelper;
    }

    /**
     * 乐观锁插件
     *
     * @return
     */
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}

添加UserController

package com.blackcat.mybatis.controller;

import com.blackcat.mybatis.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p> :Controller
 * @author : blackcat
 * @date : 2020/1/18 13:20
 */
@RestController
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 新增测试
     */
    @RequestMapping("/addUser")
    public Object addUser(String userName) {
        return userService.addUser(userName);
    }

    /**
     * 查询测试
     */
    @RequestMapping("/findUserList")
    public Object findUserList(Integer pageNo, Integer pageSize) {
        return userService.findUserList(pageNo, pageSize);
    }
}

添加UserMapper.xml

<?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.blackcat.mybatis.mapper.UserMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.blackcat.mybatis.entity.User">
        <id column="USER_ID" property="userId"/>
        <result column="USER_NAME" property="userName"/>
    </resultMap>
</mapper>

配置文件application.yml

server:
  port: 8090

  #dataSource set
spring:
  datasource:
    name: hejrDataSource
    url: jdbc:mysql://192.168.31.77:4306/testdata?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false
    username: root
    password: 111111
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    filters: stat
    maxActive: 20
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20


#mybatis plus
mybatis-plus:
  mapper-locations: classpath:mapper/*Mapper.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.blackcat.mybatis.entiry
  #typeEnumsPackage: com.baomidou.springboot.entity.enums
  global-config:
    #刷新mapper 调试神器
    db-config:
      #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
      #idtype: 0
      #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
      field-strategy: not_empty
      #驼峰下划线转换
      column-underline: true
      #数据库大写下划线转换
      #capitalmode: true
      #逻辑删除配置
      logic-delete-value: 1
      logic-not-delete-value: 0
      db-type: mysql
    refresh: true
      #自定义填充策略接口实现
      #metaobjecthandler: com.baomidou.springboot.xxx
    #自定义SQL注入器
  #sqlinjector: com.baomidou.mybatisplus.extension.injector.LogicSqlInjector
  configuration:
    # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true
    cache-enabled: false

logging.level.com.blackcat.mybaits.mapper: debug

运行结果

在这里插入图片描述
在这里插入图片描述

注解

@TableName:数据库表相关

@TableId:表主键标识

@TableField:表字段标识

  • @TableField(exist = false):表示该属性不为数据库表字段,但又是必须使用的。
  • @TableField(exist = true):表示该属性为数据库表字段。

@TableLogic:表字段逻辑处理注解(逻辑删除)

问题

Unknown column ‘xxx’ in ‘field list’

该错误一般情况下是实体类与数据库字段不匹配导致。例如:名称有下划线之类的,与实体类不一致。
也还有其他情况出现:
例如:
实体类中使用@Transient注解,数据库中并不会存在该字段,但是又是必须使用字段。
这时当时用当使用mybatis-plus自带的查询时,如selectById(key)之类的就会报标题标注错误。
解决方式:
在字段上方加入@TableField(exist = false)注解(表示该属性不为数据库表字段,但又是必须使用的。)

关于’getBaseMapper()’ in ‘com.baomidou.mybatisplus.extension.service.impl.ServiceImpl’ clashes with…

问题原因:mapper类没有继承BaseMapper
示例:

// Mapper类
public interface UserMapper{// 没有继承extends BaseMapper<User> 

}
// Service类
public interface IUserService extends IService<User> {
}
// ServiceImpl类
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {// 此处会报错
}

解决:UserMapper类继承BaseMapper

ClassNotFoundException: org.mybatis.logging.LoggerFactory

依赖冲突,查看自己依赖是否错误

  • spring boot整合mybatis maven 依赖
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.1.1</version>
</dependency>
<dependency>
	<groupId>com.github.pagehelper</groupId>
	<artifactId>pagehelper</artifactId>
	<version>5.1.4</version>
</dependency>
<dependency>
	<groupId>com.github.pagehelper</groupId>
	<artifactId>pagehelper-spring-boot-autoconfigure</artifactId>
	<version>1.2.5</version>
</dependency>
  • spring boot整合mybatis-plus maven 依赖
<!-- mybatisPlus 核心库 -->
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
	<version>3.1.0</version>
</dependency>
<!--分页-->
<dependency>
	<groupId>com.github.pagehelper</groupId>
	<artifactId>pagehelper-spring-boot-starter</artifactId>
	<version>1.2.12</version>
</dependency>

示例代码

源码 简单版:https://gitee.com/kylin_lawliet/springboot-demos/tree/master/springboot-mybaits-plus
源码 基础版:https://gitee.com/kylin_lawliet/springboot-demos/tree/master/springboot-mybatis-plus2

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值