MyBatis Plus到底有多好用

一句话:MyBatis Plus很好用!
基本的使用就不赘述了,移至官网(https://mp.baomidou.com/),在这里我分享点高级的。

1. 多表关联

思路:多表关联查询类似于对一个视图(View)进行检索,如果数据库中没有定义这个视图的话,可以在Model类中进行定义。
下面的例子定义了2个实体表,1个关联表:

字段 名称
id 主键ID
group_id 组ID
group_name 组名

用户

字段 名称
id 主键ID
user_id 用户ID
user_name 用户名

组_用户_关联

字段 名称
id 主键ID
group_id 组ID
user_id 用户ID

现在如果想生成一个带有组名称和带有用户名称的实体信息的话, 可以这么定义:

/**
 * 定义组和用户的关联关系
 */
@TableName("t_gourp_user_relation r inner join t_group g on r.group_id = g.group_id inner join t_user u on r.user_id = u.user_id")
public class GourpUserRelation {
    /**
     * ID
     */
    @TableId(value = "r.id", type = IdType.AUTO)
    private String id;
    
    /**
     * 组ID
     */
    @TableField(value = "r.group_id")
    private String groupId;
    
    /**
     * 组名
     */
    @TableField(value = "g.group_name")
    private String groupName;
    
    /**
     * 用户ID
     */
    @TableField(value = "r.user_id")
    private String userId;
    
    /**
     * 用户名
     */
    @TableField(value = "u.user_name")
    private String userName;

这样,再查询的时候就可以对待普通实体一样,利用MP的LambdaQuery进行方便的查询了。

2. 构造自动查询模型

还在写这种Lambda查询么?太LOW了。

public class UserModel {
	
	/**
     * 用户ID
     */
    @TableId(value = "user_id", type = IdType.AUTO)
    private String userId;
   
    /**
     * 用户名
     */
    @TableField(value = "user_name")
    private String userName;
}
Wrappers.<User>lambdaQuery()
  .eq(userId != null, User::getUserId, userId)
  .like(userNameLike != null, User::getUserName, userNameLike)
  .in(userIds != null && !userIds.isEmpty(), User::getUserId, userIds)

改进后的写法:
全局配置查询策略

mybatis-plus:
  global-config:
  	db-config:
  	  selectStrategy: NOT_EMPTY

扩展条件SQL类型

public class SqlConditionEx {
	public static final String IN = "%s IN <foreach item=\"item\" collection=\"%s\" separator=\",\" open=\"(\" close=\")\" index=\"\">#{item}</foreach>"
}

每个字段固定的查询类型封装到实体扩展类里

public class UserQueryModel extends UserModel {
    
    /**
     * 用户名模糊查询
     */
    @TableField(value = "user_name", select = false, condition = SqlCondition.LIKE)
	private String userNameLike;

    /**
     * 用户ID列表
     */
    @TableField(value = "user_id", select = false, condition = SqlConditionEx.IN)
	private String[] userIds;
}

根据实体扩展类对象自动构造Lambda Query

UserQueryModel userQueryModel = new UserQueryModel(userId, userIds, userNameLike)
Wrappers.<User>lambdaQuery(userQueryModel);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章