简体   繁体   中英

FetchType.LAZY on Parent's @OneToMany and FetchType.EAGER on Child's @ManyToOne

I have the following model:

public class Parent {

  @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "parent",
      orphanRemoval = true)
  @Fetch(FetchMode.SELECT)
  private List<Child> children = new ArrayList<Child>();

}

public class Child {

  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "parent_id")
  private Parent parent;

}

Is this the correct usage of FetchType ? Am I allowed to use FetchType.LAZY on Parent, but FetchType.EAGER on the Child object? What are the effects of setting the Child's FetchType to FetchType.LAZY as well?

It is ok. You can set the fetch type differently in each part of the relationship.

If you set FetchType.LAZY in the Child, when you get a child entity you will not get directly an instance of the Parent, unless you navigate the relationship inside a managed context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM