本文最后更新于 2025-01-09,转载请标明原作者!

MybatisPlus通过扫描实体类,并基于反射获取实体类信息作为数据库表信息。

  • 类名驼峰转下划线作为表名

  • 名为id的字段作为主键

  • 变量名驼峰转下划线作为表的字段名

常见注解

  • @TableName 用来指定表名

  • @TableId 用来指定表中的主键字段信息

  • @TableField 用来指定表中的普通字段信息

使用@TableField注解常见情况:

  • 成员变量名与数据库字段不一致。

  • is开头的成员变量名,也需要使用@TableField注解。

  • 成员变量名与数据库关键字冲突,也需要使用@TableField注解。

  • 数据库不存在的字段。

@TableName("tb_user")
public class User {
    @TableId(value="id", type= IdType. AUTO )
    private Long id;
    @TableField("username")
    private String name;
    @TableField("is_married")
    private Boolean isMarried;
    @TableField("`order`")
    private Integer order;
    @TableField(exist = false)
    private String address;    //数据库不存在的字段
}

@TableId注解的IdType枚举:

  • AUTO 数据库自增长

  • INPUT 通过set方法自行输入

  • ASSIGN_ID 分配ID,接口IdentifierGenerator的方法nextId来生成id,默认实现类

常见配置

MyBatisPlus的配置项继承了MyBatis原生配置和一些自己特有的配置。例如:

mybatis-plus:
  type-aliases-package:  com.qbyte.mp.domain.po  # 别名扫描包
  mapper-locations:  "classpath*:/mapper/**/*.xml"  # Mapper.xml文件地址,默认值
  configuration:
    map-underscore-to-camel-case:  true  # 是否开启下划线和驼峰的映射
    cache-enabled:  false  # 是否开启二级缓存
  global-config:
    db-config:
    id-type:  assign_id  # 表id默认为雪花算法生成
    update-strategy:  not_null  # 更新策略:只更新非空字段

Service与Mapper继承

Service继承示例:

public interface IMovieService extends IService<Movie> {

    Result updateMovie(Movie movie);

    Result deleteMovie(Integer id);

    Result<Page<Movie>> getUserPublish(Integer userId, Integer current);

    Result publishMovie(Movie movie);

    Result<Page<Movie>> searchMovie(SearchMovieDto searchMovieDto);

    Result hotMovies();

    Result getMovieById(Integer id);

    Result editMovie(Movie movie);
}

Mapper继承示例:

@Mapper
public interface MovieMapper extends BaseMapper<Movie> {

    //查询热门电影
    @Select("SELECT * FROM (SELECT * FROM movie ORDER BY num DESC LIMIT 50) AS top_50_movies ORDER BY score DESC LIMIT 15")
    List<Movie> selectHotMovies();


}

对应的Mapper.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.example.MovieReviewSystem.mapper.MovieMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.example.MovieReviewSystem.domain.dao.Movie">
        <id column="id" property="id" />
        <result column="uid" property="uid" />
        <result column="movie_name" property="movieName" />
        <result column="year" property="year" />
        <result column="directors" property="directors" />
        <result column="writers" property="writers" />
        <result column="actors" property="actors" />
        <result column="type" property="type" />
        <result column="regions" property="regions" />
        <result column="languages" property="languages" />
        <result column="release_date" property="releaseDate" />
        <result column="run_time" property="runTime" />
        <result column="alise" property="alise" />
        <result column="score" property="score" />
        <result column="num" property="num" />
        <result column="introduction" property="introduction" />
        <result column="pic" property="pic" />
    </resultMap>

</mapper>

对应的实体类:

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Movie implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    /**
     * 上传的人
     */
    private Integer uid;

    private String movieName;

    private Integer year;

    private String directors;

    private String writers;

    private String actors;

    private String type;

    private String regions;

    private String languages;

    /**
     * 上映时间
     */
    private String releaseDate;

    /**
     * 时长
     */
    private String runTime;

    private String alise;

    private Double score;

    /**
     * 评价人数
     */
    private Integer num;

    /**
     * 简介
     */
    private String introduction;

    /**
     * 电影海报
     */
    private String pic;
}

构造器

LambdaQueryWrapper构造器用法:

//1.构造查询条件
LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
  .select(User::getId,User::getUsername,User::getInfo,User::getBalance)
  .like(User::getUsername,"o")
  .ge(User:getBalance,1000);
//2.查询
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);

这样可以避免字符串硬编码。

枚举处理器

在application.yaml加上配置:

mybatis-plus:
  configuration:
    default-enum-type-handler:  com.baomidou.mybatisplus.core.handlers.MybatisEnumTypeHandler

示例:

public enum UserStatus{
  NORMAL(1,"正常"),
  FROZEN(2,"冻结");

  @EnumValue    //@EnumValue注解标记,将标记的成员变量值与数据库相关列对应
  private final int value;
  @JsonValue    //@JsonValue注解标记,返回对应成员变量,此处返回desc的值
  private final String desc;

  UserStatus(int value,String desc){
    this.value = value;
    this.desc = desc;
  }
}

Json处理器

@Data
@TableName(value = "user",autoResultMap = true)
public class User{
  private Long id;
  private String userName;
  @TableField(typeHandler = JacksonTypeHandler.class)
  private UserInfo info;
}
@Data
public class UserInfo{
  private Integer age;
  private String intro;
  private String gender;
}

这样处理之后,便可以将数据库里的Json文本转换成对应的实体类对象。

分页插件

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //创建并添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

这样配置之后就可以使用Page类来分页查询。