马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
各人好哇!不知道各人在利用JPA的时间有没有试用过实体图(EntityGraph)举行查询呢?它的功能很强大,
比如可以用来规避各人经常遇到的 n+1 的标题。
那么你了不相识怎样在"自界说中心表"的情况下去利用实体图查询呢?假如不太相识,那么就来跟着我看一下吧!
为了方便演示,后续的项目情况默认视为在 spring-boot-starter-data-jpa 中喔~
实体界说
起首,我们先来看看平凡的多对多实体是怎样界说、查询的。假设:我们有一个账户(account)和权限(permission)表,
它们之间是多对多关系,中心表为 account_permission 。
那么,先来界说它们的实体类:
- // Account.java
- @Entity
- public class Account {
-
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
- @Column(nullable = false)
- private String name;
- @ManyToMany
- @JoinTable(name = "account_permission")
- private Set<Permission> permissions = new HashSet<>();
- }
- // Permission.java
- @Entity
- public class Permission {
-
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
- private String name;
- @ManyToMany(mappedBy = "permissions")
- private Set<Account> accounts = new HashSet<>();
- }
复制代码 为了演示省事儿,省略掉 getter、setter 之类的东西咯。
然后,在 Account 中添加实体图形貌。
- @Entity
- @NamedEntityGraph(
- name = Account.ALL_GRAPH,
- attributeNodes = {
-
-
- @NamedAttributeNode("permissions")
- }
- )
- public class Account {
-
-
- public static final String ALL_GRAPH = "ACCOUNT.ALL";
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
- @Column(nullable = false)
- private String name;
- @ManyToMany
- @JoinTable(name = "account_permission")
- private Set<Permission> permissions = new HashSet<>();
- }
复制代码 接下来,界说一个 Repository 并利用图查询,来看看效果:
- public interface AccountRepository extends JpaRepository<Account, Integer> {
-
-
- // 使用具有命名的图查询
- @EntityGraph(Account.ALL_GRAPH)
- List<Account> findAllBy();
- }
复制代码 [code][/code]
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!qidao123.com:ToB企服之家,中国第一个企服评测及软件市场,开放入驻,技术点评得现金 |