我有一个具有多个单向OneToMany关系的实体,如下所示。如何在一个查询中获取所有这些字段?如果我最多有10个具有OneToMany关系的Arraylist,那将是最好的方法?
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "members")
public class Member extends Auditable<String> {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Setter(AccessLevel.NONE)
private Long id;
@OneToOne
private Gender gender;
private String lastName;
private String firstName;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@JoinColumn(name = "person_id")
private List<Phone> phoneList = new ArrayList<>();
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@JoinColumn(name = "person_id")
private List<EMail> eMailList = new ArrayList<>();
// more Lists with OneToMany relationship
}
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "emails")
public class EMail extends Auditable<String> {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Setter(AccessLevel.NONE)
private Long id;
private Type type;
private String value;
}
我尝试了在MemberRepository类中执行以下步骤,该步骤以MultipleBagFetchException结尾:
@Query("SELECT m " +
"FROM Member m " +
"LEFT JOIN FETCH m.eMailList " +
"LEFT JOIN FETCH m.phoneList " +
"WHERE m.memberId = ?1")
Optional<Member> findByMemberIdWithAllInfoQuery(Long id); // MultipleBagFetchException
然后我尝试使用此信息https://vladmihalcea.com/hibernate-multiplebagfetchexception/执行以下步骤,该信息也无法正常工作:
public Optional<Member> findMemberWithAllFieldsQuery(Long memberId) {
Member _member = entityManager.createQuery(
"SELECT DISTINCT m " +
"FROM Member m " +
"LEFT JOIN FETCH m.eMailList " +
"WHERE m.memberId = :id ", Member.class)
.setParameter("id", memberId)
.setHint(QueryHints.HINT_PASS_DISTINCT_THROUGH, false)
.getSingleResult();
_member = entityManager.createQuery(
"SELECT DISTINCT m " +
"FROM Member m " +
"LEFT JOIN FETCH m.phoneList " +
"WHERE m in :member ", Member.class)
.setParameter("member", _member)
.setHint(QueryHints.HINT_PASS_DISTINCT_THROUGH, false)
.getSingleResult();
return Optional.of(_member);
}
感谢您的帮助/提示!
尝试使用Set而不是List?将集合更改为Set
后,我遇到了此异常并解决了该问题@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@JoinColumn(name = "person_id")
private Set<Phone> phoneList = new HashSet<>();
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@JoinColumn(name = "person_id")
private Set<EMail> eMailList = new HashSet<>();