如何在一次查询中获取具有所有子关联的实体?
How to fetch an entity with all children associations in one query?
我有一个名为 Ave
的 JPA 实体,它有两个子关联,如下所示:
@Entity
@Table(name = "ave")
@Access(AccessType.FIELD)
public class Ave implements Serializable {
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE, targetEntity = Contact.class)
@JoinTable(name = "ave_contact", joinColumns = @JoinColumn(name = "ave_id"), inverseJoinColumns = @JoinColumn(name = "potentialbuyer_id"))
@Fetch(value = FetchMode.SUBSELECT)
private List<Contact> allPotentialBuyers = new ArrayList<>();
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity = Bid.class, mappedBy = "ave")
@Fetch(value = FetchMode.JOIN)
private Set<Bid> bids = new HashSet<>();
我想在一个 JPQL 查询中加载所有 Ave
实体,所有 bids
和所有 allPotentialBuyers
(可能有多个 SQL 选择)。 (怎么)可能?
使用left join fetch
:
entityManager.createQuery(
"select a " +
"from Ave a " +
"left join fetch a.allPotentialBuyers " +
"left join fetch a.bids", Ave.class
).getResultSet();
我有一个名为 Ave
的 JPA 实体,它有两个子关联,如下所示:
@Entity
@Table(name = "ave")
@Access(AccessType.FIELD)
public class Ave implements Serializable {
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE, targetEntity = Contact.class)
@JoinTable(name = "ave_contact", joinColumns = @JoinColumn(name = "ave_id"), inverseJoinColumns = @JoinColumn(name = "potentialbuyer_id"))
@Fetch(value = FetchMode.SUBSELECT)
private List<Contact> allPotentialBuyers = new ArrayList<>();
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity = Bid.class, mappedBy = "ave")
@Fetch(value = FetchMode.JOIN)
private Set<Bid> bids = new HashSet<>();
我想在一个 JPQL 查询中加载所有 Ave
实体,所有 bids
和所有 allPotentialBuyers
(可能有多个 SQL 选择)。 (怎么)可能?
使用left join fetch
:
entityManager.createQuery(
"select a " +
"from Ave a " +
"left join fetch a.allPotentialBuyers " +
"left join fetch a.bids", Ave.class
).getResultSet();