进阶示例:用户与用户发布的文章的场景

场景一:获取用户信息的同时想获取用户的全部发布记录。

1、构建实体对象

  1. @Data
  2. @Table(comment = "文章")
  3. public class Article {
  4. @ColumnComment("主键")
  5. private String id;
  6. @ColumnComment("标题")
  7. private String title;
  8. @Column(comment = "内容", type = MySqlTypeConstant.MEDIUMTEXT)
  9. private String content;
  10. @ColumnComment("发布人")
  11. private String publishedUserId;
  12. }
  1. @Data
  2. @Table(comment = "用户信息")
  3. public class User {
  4. @ColumnComment("主键")
  5. private String id;
  6. @ColumnComment("用户名")
  7. private String username;
  8. @ColumnComment("密码")
  9. private String password;
  10. // 关联该用户发布的所有文章()
  11. @BindEntity(conditions = @JoinCondition(selfField = "id", joinField = "publishedUserId"))
  12. private List<Article> articles;
  13. }

2、数据查询

参考例1

场景二:获取用户信息的同时只想获取用户已通过审核的发布记录,并且根据发布时间倒序排序。(通过自定义SQL条件)

1、构建实体对象

  1. @Data
  2. @Table(comment = "文章")
  3. public class Article {
  4. @ColumnComment("主键")
  5. private String id;
  6. @ColumnComment("标题")
  7. private String title;
  8. @Column(comment = "内容", type = MySqlTypeConstant.MEDIUMTEXT)
  9. private String content;
  10. @ColumnComment("发布人")
  11. private String publishedUserId;
  12. // 新增字段
  13. @ColumnComment("审核: 0 不通过、1 通过")
  14. private int audit;
  15. @ColumnComment("发布时间(时间戳)")
  16. private Long publishedTime;
  17. }
  1. @Data
  2. @Table(comment = "用户信息")
  3. public class User {
  4. @ColumnComment("主键")
  5. private String id;
  6. @ColumnComment("用户名")
  7. private String username;
  8. @ColumnComment("密码")
  9. private String password;
  10. // 关联该用户发布的所有文章("audit = 1" 表示的是Article下的audit为1的情况,customCondition的值只能是被关联表下的字段值,且会以and的形式添加在查询条件末尾。)
  11. @BindEntity(conditions = @JoinCondition(selfField = "id", joinField = "publishedUserId"), customCondition = "audit = 1", orderBy = @JoinOrderBy(field = "publishedTime", isAsc = false))
  12. private List<Article> articles;
  13. }

2、数据查询

参考例1

场景三:获取用户信息的同时只想获取用户最新三条已通过审核的发布记录,并且根据发布时间倒序排序。(通过自定义SQL条件)

3.5.2-EXT140 及之后的版本才支持 last 属性

1、构建实体对象

文章实体 见场景二

  1. @Data
  2. @Table(comment = "用户信息")
  3. public class User {
  4. @ColumnComment("主键")
  5. private String id;
  6. @ColumnComment("用户名")
  7. private String username;
  8. @ColumnComment("密码")
  9. private String password;
  10. // 关联该用户发布的所有文章("audit = 1" 表示的是Article下的audit为1的情况,customCondition的值只能是被关联表下的字段值,且会以and的形式添加在查询条件末尾。)
  11. @BindEntity(conditions = @JoinCondition(selfField = "id", joinField = "userId"), customCondition = "audit = 1", orderBy = @JoinOrderBy(field = "publishedTime", isAsc = false), last = "limit 3")
  12. private List<Article> articles;
  13. }