在JPA中,利用实体图查询具有自界说中心表的多对多实体 [复制链接]
发表于 2026-2-27 15:24:41 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
各人好哇!不知道各人在利用JPA的时间有没有试用过实体图(EntityGraph)举行查询呢?它的功能很强大,
比如可以用来规避各人经常遇到的 n+1 的标题。
那么你了不相识怎样在"自界说中心表"的情况下去利用实体图查询呢?假如不太相识,那么就来跟着我看一下吧!
   为了方便演示,后续的项目情况默认视为在 spring-boot-starter-data-jpa 中喔~
  实体界说

起首,我们先来看看平凡的多对多实体是怎样界说、查询的。假设:我们有一个账户(account)和权限(permission)表,
它们之间是多对多关系,中心表为 account_permission 。
那么,先来界说它们的实体类:
  1. // Account.java
  2. @Entity
  3. public class Account {
  4.    
  5.    
  6.     @Id
  7.     @GeneratedValue(strategy = GenerationType.IDENTITY)
  8.     private Integer id;
  9.     @Column(nullable = false)
  10.     private String name;
  11.     @ManyToMany
  12.     @JoinTable(name = "account_permission")
  13.     private Set<Permission> permissions = new HashSet<>();
  14. }
  15. // Permission.java
  16. @Entity
  17. public class Permission {
  18.    
  19.    
  20.     @Id
  21.     @GeneratedValue(strategy = GenerationType.IDENTITY)
  22.     private Integer id;
  23.     private String name;
  24.     @ManyToMany(mappedBy = "permissions")
  25.     private Set<Account> accounts = new HashSet<>();
  26. }
复制代码
  为了演示省事儿,省略掉 getter、setter 之类的东西咯。
  然后,在 Account 中添加实体图形貌。
  1. @Entity
  2. @NamedEntityGraph(
  3.         name = Account.ALL_GRAPH,
  4.         attributeNodes = {
  5.    
  6.    
  7.                 @NamedAttributeNode("permissions")
  8.         }
  9. )
  10. public class Account {
  11.    
  12.    
  13.     public static final String ALL_GRAPH = "ACCOUNT.ALL";
  14.     @Id
  15.     @GeneratedValue(strategy = GenerationType.IDENTITY)
  16.     private Integer id;
  17.     @Column(nullable = false)
  18.     private String name;
  19.     @ManyToMany
  20.     @JoinTable(name = "account_permission")
  21.     private Set<Permission> permissions = new HashSet<>();
  22. }
复制代码
接下来,界说一个 Repository 并利用图查询,来看看效果:
  1. public interface AccountRepository extends JpaRepository<Account, Integer> {
  2.    
  3.    
  4.     // 使用具有命名的图查询
  5.     @EntityGraph(Account.ALL_GRAPH)
  6.     List<Account> findAllBy();
  7. }
复制代码
[code][/code]
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!qidao123.com:ToB企服之家,中国第一个企服评测及软件市场,开放入驻,技术点评得现金
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表