Java/后端

实体映射、CRUD 与分页配置

实体字段映射注解、MyBatis-Plus 的 CRUD 调用、分页插件配置、Maven 依赖及常见坑。

一、实体类字段映射

1. 主键 @TableId

@TableId
private Long id;
  • 标记主键字段。
  • 默认主键名为 id,策略为雪花算法(ASSIGN_ID)。
  • 可指定 @TableId(type = IdType.AUTO) 使用数据库自增。

2. 列名映射 @TableField

@TableField(value = "create_time")
private LocalDateTime createTime;

@TableField(value = "update_time")
private LocalDateTime updateTime;
  • 指定 Java 字段与数据库列的对应关系。
  • 驼峰命名(createTime)与下划线命名(create_time)不一致时使用。
  • 若列名是 MySQL 关键字,需加反引号,如 @TableField(value = "\order`”)`。

3. 时间格式化 @JsonFormat

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField(value = "update_time")
private LocalDateTime updateTime;
  • 控制 JSON 序列化时的时间格式。
  • 不加时,LocalDateTime 默认输出 ISO 格式(2026-09-16T10:30:00),前端不易解析。
  • 加后输出 2026-09-16 10:30:00
  • 依赖 Jackson(Spring Boot 默认自带)。

二、Mapper 接口的 CRUD 调用

1. 查询列表 selectList

@GetMapping
public List<User> getAll() {
    return userMapper.selectList(new LambdaQueryWrapper<>());
}
  • 返回 List<T>
  • 条件构造器推荐使用 LambdaQueryWrapper,语义比 LambdaUpdateWrapper 更准确。

2. 分页查询 selectPage

@GetMapping
public Page<User> getAll() {
    return userMapper.selectPage(new Page<>(1, 10), new LambdaQueryWrapper<>());
}
  • Page<T>new Page<>(current, size)current 为当前页,size 为每页条数。
  • 返回 Page<User>,包含总条数、总页数、当前页数据等。
  • 必须配置分页插件,否则会退化为内存分页(全表查询),性能极差。

三、分页插件配置(核心)

@Configuration
@MapperScan("com.example.demo.mapper")
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
组件作用
MybatisPlusInterceptor插件容器
PaginationInnerInterceptor分页拦截器,真正实现分页
DbType.MYSQL指定数据库类型,不同数据库分页 SQL 语法不同

注意:若配置多个插件,分页拦截器必须放在最后。


四、Maven 依赖补充

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-jsqlparser</artifactId>
</dependency>
  • MyBatis-Plus 3.5.9 之后,分页等依赖 SQL 解析的功能被抽离到该模块。
  • 不加此依赖,分页插件可能无法生效或报错。
  • 版本通常由父工程管理,无需手动指定。

五、常见坑与注意事项

  1. 分页不生效:检查是否配置了 PaginationInnerInterceptor
  2. 时间格式不对LocalDateTime 默认返回 ISO 格式,加 @JsonFormat 修正。
  3. 表名报错:MySQL 关键字表名(如 userorder)必须加反引号。
  4. 字段映射不上:检查驼峰转下划线规则,不一致时加 @TableField
  5. LambdaUpdateWrapper 用于查询:语法能跑,但建议用 LambdaQueryWrapper

六、总结

知识点核心内容
字段映射@TableId(主键)、@TableField(列名)、@JsonFormat(时间格式)
查询列表selectList(wrapper)
分页查询selectPage(page, wrapper)
分页插件MybatisPlusInterceptor + PaginationInnerInterceptor
Maven 依赖mybatis-plus-jsqlparser 支持分页等 SQL 解析