一句話: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);