JPA嵌套对象LAZY FETCH仅返回第一个对象

6l7fqoea  于 2023-08-06  发布在  其他
关注(0)|答案(2)|浏览(113)

我有以下几点。

@Data
@Getter
@Setter
@Accessors(fluent = false, chain = true)
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@MappedSuperclass
@Slf4j
class Base {
  private Timestamp createdTime;
  private Timestamp modifiedTime;
  private String createdBy;
  private String modifiedBy;
  private Boolean deleted = false;
}

@Getter
@Setter
@Builder
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "account")
@SQLDelete(sql = "UPDATE account SET deleted = true WHERE account_id = ?")
@Where(clause = "deleted=false")
class Account {
  @Id
  @EqualsAndHashCode.Include()
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long accountId;

  @Builder.Default
  @OneToMany(fetch = FetchType.LAZY, mappedBy = "account", cascade = {CascadeType.ALL})
  private Set<Collab> collaborators = new HashSet<>(0);
  private String objId;
}

class Collab {
  @Id
  @EqualsAndHashCode.Include()
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long collabId;
  private String email;
  private String role;
  @JsonBackReference
  @JoinColumn(name = "accountId")
  @ManyToOne(fetch = FetchType.EAGER)
  private Account account;
}

public interface AccountRepo {
  Optional<Account> findByObjId(String objId);
}

字符串
即使数据库中的单个帐户有多个协作。当我检查AccountRepo.findByObjId(或findAll)方法的响应时,对于任何帐户对象,collaborators中只有1个元素。我错过了什么?
PS:@EqualsAndHashCode.Include()来自Lombok岛

mjqavswn

mjqavswn1#

当您检查AccountRepo.findByObjId或findAll的响应时,您可能只看到collaborators集中的一个元素,因为延迟加载机制按需加载相关的Collab实体。如果您在检索Account对象后访问collaborators集,它应该触发从数据库加载关联的Collab实体。
尝试为协作者实现一个getter方法,如下所示

public Set<Collab> getCollaborators() {
  return collaborators;
}

字符串
之后,您可以像这样访问协作者

Optional<Account> accountOptional = accountRepo.findByObjId(objId);
if (accountOptional.isPresent()) {
  Account account = accountOptional.get();
  Set<Collab> collaborators = account.getCollaborators(); // Load collaborators
}

jbose2ul

jbose2ul2#

我在BaseClass中有以下注解,这导致了Hashcode/Equals的问题,最终导致了Set中的项目。

@EqualsAndHashCode(onlyExplicitlyIncluded = true)

字符串

相关问题