1
Entity{
    String code;
    String parentCode;
...
    @ManyToOne
    @JoinColumn(name="parentCode",referencedColumnName="code")
    Entity parentEntity;
}

My entity class is like this. what i want to do is using findAll() to get an entity list with each entity get its own direct parent. But spring jpa will get parent's parent until the root , i need to avoid this. Thank you!

hankjy
  • 51
  • 5

2 Answers2

0

Since a default fetch type for a @ManyToOne relation is an FetchType.EAGER I think you have just add a fetch type as LAZY explicitly:

Entity{
    String code;
    String parentCode;
...
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="parentCode",referencedColumnName="code")
    Entity parentEntity;
}
Yuriy Tsarkov
  • 2,461
  • 2
  • 14
  • 28
0

It's not about Spring JPA but JPA itself. When you add a relationship, following defaults apply unless specified otherwise.

@xxToOne - FetchType.EAGER

@xxToMany- FetchType.LAZY

So, in your example you have a @ManyToOne which has a default EAGER fetch and one join query is appended. If your parent has another @xxToOne it adds one more join and so on. It's good to know the boundaries of your entities and decide which type of FetchType is required.

Even if you add like this:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="parentCode",referencedColumnName="code")
Entity parentEntity;

.. if you parent has more relationships you might be getting everything loaded while fetching parent. Thus, all relationships need to be Lazy. It's a design choice based on entities.

But be aware about the ORM's N+1 problem : JPA Hibernate n+1 issue (Lazy & Eager Diff)

Karthik R
  • 5,523
  • 2
  • 18
  • 30
  • i hope this work ,but it seems not. I still get the infinite recursivion until fatherId is null – hankjy Nov 07 '18 at 09:05