【问题标题】:jpaRepository findAll with parent and child use pagablejpaRepository findAll 与父子使用可分页
【发布时间】:2017-04-18 01:24:20
【问题描述】:

我正在使用spring bootjpa,我正在尝试使用jparepository 从父实体和子实体获取数据。

父实体:

@Entity
@Table(name = "parent")
public class Parent {
  @Id
  private int id;

  private String name;

  @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
  private Set<Child> children;
}

子实体:

@Entity
@Table(name = "child")
public class Child {

  @Id
  private int id;

  private String name;

  private int parent_id;

  @ManyToOne
  @JoinColumn(name = "parent_id", referencedColumnName = "id")
  private Parent parent;

jpaRepository:

public interface ParentRepository extends JpaRepository<Parent, Integer>, JpaSpecificationExecutor<Parent> {

}

我将 fecth 设置为 FetchType.LAZY 的原因是有时我只想让父母没有孩子。

所以,这是我的问题: 当我使用

parentRepository.findAll(pagable);

结果只包含父母,不包含孩子,但我希望结果包含孩子,在某些情况下我不想要它。怎么写?

【问题讨论】:

标签: spring hibernate spring-data-jpa


【解决方案1】:

要获取子集合,您可以声明一个实体图。像这样的:

@NamedEntityGraph(
    name = "parent.withChildren",
    attributeNodes = {
            @NamedAttributeNode("children")
    }
)

然后将其与存储库方法一起使用:

@EntityGraph("parent.withChildren")
Page<Parent> findWithChidren(Pageable page);

【讨论】:

  • 这也是我推荐的解决方案!我知道有一种不同的方法,调用“getChild”,但是你需要这样做的时间太混乱了,所以连接没有关闭,避免了 Lazy 异常。使用 JPA 2.1 解决方案保持简单。 NamedEntityGraph 获胜!
猜你喜欢
  • 2017-01-24
  • 2015-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-25
  • 1970-01-01
相关资源
最近更新 更多