简体   繁体   English

避免在 Spring 数据 JPA 中获取 @ManyToOne 属性

[英]Avoid fetching @ManyToOne property in Spring data JPA

I have three entities as below.我有以下三个实体。 I'm using Lombok based getters and setters:我正在使用基于 Lombok 的 getter 和 setter:

@Getter
@Setter
@EqualsAndHashCode(callSuper = true, exclude = { "cClasses"})
class AClass {
   // some properties
   @OneToMany(mappedBy = "aClass", orphanRemoval = true)
   private List<CClass> cClasses;
}

class BClass {
  // some properties
}

@Getter
@Setter
@EqualsAndHashCode(callSuper = true, exclude = { "aClass", "bClass"})
class CClass {
  // other properties
  // this is bidirectional
  @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  @JoinColumn(name = "A_ID", referencedColumnName = "A_ID")
  private AClass aClass;

  // this is unidirectional
  @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  @JoinColumn(name = "B_ID", referencedColumnName = "B_ID")
  private BClass bClass;
}

And by JPA repository class looks like as below:并通过 JPA 存储库类如下所示:

@Repository
public interface CClassRepository extends JpaRepository<CClass, Long> {
  List<CClass> findByBClassBidIn(List<Long> ids);
}

The output is coming as expected but the performance is very poor.输出按预期进行,但性能很差。 I can see in logs that select queries for all AClass is also getting executed.我可以在日志中看到所有 AClass 的选择查询也正在执行。 How can I avoid the calls to @ManyToOne property aClass.如何避免调用 @ManyToOne 属性 aClass。

I tried using @JsonManagedReference and @JsonIgnore on aClass property of CClass.我尝试在 CClass 的 aClass 属性上使用 @JsonManagedReference 和 @JsonIgnore。 But still it is fetching those records when I'm calling repository method.但是当我调用存储库方法时它仍然在获取这些记录。 Please suggest how to solve this problem.请建议如何解决这个问题。

It's better to invert the relationship, so ClassB can know about ClassC最好把关系ClassC ,让ClassB知道ClassC

class BClass {
  @OneTOMany(...)
  private CClass cClass;
}

@Repository
public interface BClassRepository extends JpaRepository<BClass, Long> {

  @Query("select ClassB.cClass where ClassB.id is in `ids`") // might be wrong syntax
  List<CClass> findCclassesByBClassIdIn(List<Long> ids);
}

它只查询一次数据库,即从所有者一侧查询数据库,即带有@JoinColumn 注释的一侧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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