1

I'm using spring boot and jpa, I'm trying to get data from parent entity and child entity using jparepository.

Parent Entity:

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

  private String name;

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

Child Entity:

@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> {

}

the reason I set the fecth to FetchType.LAZY is that sometimes I just want to get parent without child.

So, here is my question: when I use

parentRepository.findAll(pagable);

the result only contains parents, not child, but I want the result to contain children, and in some situation I don't want it. how to write it ?

Harshal Patil
  • 6,659
  • 8
  • 41
  • 57
Jason.shen
  • 41
  • 1
  • 6
  • You can do this with @Transactinal annotation. For more details refer this answer http://stackoverflow.com/questions/26611173/jpa-jta-transactional-spring-annotation/26615390#26615390 – Harshal Patil Dec 03 '16 at 17:57

1 Answers1

1

To fetch children collection you can declare an entity graph. Something like this:

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

And then use it with repository methods:

@EntityGraph("parent.withChildren")
Page<Parent> findWithChidren(Pageable page);
Argb32
  • 1,365
  • 8
  • 10
  • This is the solution I would recommend as well! I know that there is a different way of doing it, invoking the "getChild" but is so confusing the time you need to do it so the connection is not closed, avoiding the Lazy exception. Keep it simple with the JPA 2.1 solution. NamedEntityGraph for the win! – E. Nikolas de Oliveira Dec 05 '16 at 13:37