AR模式(Active Record)
直接通过实体类完成对数据的增删改查。
实体类继承Model类
@Data @EqualsAndHashCode(callSuper = false) public class User extends Model<User> { private Long id; @TableField(condition = SqlCondition.LIKE) private String name; private Integer age; private String email; private Long managerId; private LocalDateTime createTime; }1.
Model类中封装了很多增删改查方法,不用使用UserMapper即可完成对数据的增删改查。
查询所有用户信息
@Test public void test(){ User user = new User(); user.selectAll().forEach(System.out::println); }
@Getter public enum IdType { /** * 数据库ID自增 */ AUTO(0), /** * 该类型为未设置主键类型(将跟随全局) */ NONE(1), /** * 用户输入ID * <p>该类型可以通过自己注册自动填充插件进行填充</p> */ INPUT(2), /* 以下3种类型、只有当插入对象ID 为空,才自动填充。 */ /** * 全局唯一ID (idWorker) */ ID_WORKER(3), /** * 全局唯一ID (UUID) */ UUID(4), /** * 字符串全局唯一ID (idWorker 的字符串表示) */ ID_WORKER_STR(5); private final int key; IdType(int key) { this.key = key; } }
在实体类中对应数据库中的主键id属性上标注注解TableId(type='xxx')即可完成主键配置。
@TableId(type = IdType.AUTO) private Long id;
这种配置方式的主键策略只能在该表中生效,但是其他表还需要进行配置,为了避免冗余,麻烦,MybatisPlus提供了全局配置,在配置文件中配置主键策略即可实现。
mybatis-plus: mapper-locations: mapper/*.xml global-config: db-config: id-type: auto
- 如果全局策略和局部策略全都设置,局部策略优先。
基本配置
mybatis-plus: mapper-locations: mapper/*.xml global-config: db-config: # 主键策略 id-type: auto # 表名前缀 table-prefix: t # 表名是否使用下划线间隔,默认:是 table-underline: true # 添加mybatis配置文件路径 config-location: mybatis-config.xml # 配置实体类包地址 type-aliases-package: org.ywb.demo.pojo # 驼峰转下划线 configuration: map-underscore-to-camel-case: true
- config-location & configuration 不能同时出现,否则报错。
通用Service
定义接口继承IService
public interface UserService extends IService<User>{}
定义接口的实现类
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{}
