进阶示例:用户与用户发布的文章的场景
场景一:获取用户信息的同时想获取用户的全部发布记录。
1、构建实体对象
@Data
@Table(comment = "文章")
public class Article {
@ColumnComment("主键")
private String id;
@ColumnComment("标题")
private String title;
@Column(comment = "内容", type = MySqlTypeConstant.MEDIUMTEXT)
private String content;
@ColumnComment("发布人")
private String publishedUserId;
}
@Data
@Table(comment = "用户信息")
public class User {
@ColumnComment("主键")
private String id;
@ColumnComment("用户名")
private String username;
@ColumnComment("密码")
private String password;
// 关联该用户发布的所有文章()
@BindEntity(conditions = @JoinCondition(selfField = "id", joinField = "publishedUserId"))
private List<Article> articles;
}
2、数据查询
场景二:获取用户信息的同时只想获取用户已通过审核的发布记录,并且根据发布时间倒序排序。(通过自定义SQL条件)
1、构建实体对象
@Data
@Table(comment = "文章")
public class Article {
@ColumnComment("主键")
private String id;
@ColumnComment("标题")
private String title;
@Column(comment = "内容", type = MySqlTypeConstant.MEDIUMTEXT)
private String content;
@ColumnComment("发布人")
private String publishedUserId;
// 新增字段
@ColumnComment("审核: 0 不通过、1 通过")
private int audit;
@ColumnComment("发布时间(时间戳)")
private Long publishedTime;
}
@Data
@Table(comment = "用户信息")
public class User {
@ColumnComment("主键")
private String id;
@ColumnComment("用户名")
private String username;
@ColumnComment("密码")
private String password;
// 关联该用户发布的所有文章("audit = 1" 表示的是Article下的audit为1的情况,customCondition的值只能是被关联表下的字段值,且会以and的形式添加在查询条件末尾。)
@BindEntity(conditions = @JoinCondition(selfField = "id", joinField = "publishedUserId"), customCondition = "audit = 1", orderBy = @JoinOrderBy(field = "publishedTime", isAsc = false))
private List<Article> articles;
}
2、数据查询
场景三:获取用户信息的同时只想获取用户最新三条已通过审核的发布记录,并且根据发布时间倒序排序。(通过自定义SQL条件)
3.5.2-EXT140 及之后的版本才支持 last 属性
1、构建实体对象
文章实体 见场景二
@Data
@Table(comment = "用户信息")
public class User {
@ColumnComment("主键")
private String id;
@ColumnComment("用户名")
private String username;
@ColumnComment("密码")
private String password;
// 关联该用户发布的所有文章("audit = 1" 表示的是Article下的audit为1的情况,customCondition的值只能是被关联表下的字段值,且会以and的形式添加在查询条件末尾。)
@BindEntity(conditions = @JoinCondition(selfField = "id", joinField = "userId"), customCondition = "audit = 1", orderBy = @JoinOrderBy(field = "publishedTime", isAsc = false), last = "limit 3")
private List<Article> articles;
}