Hibernate FetchMode = Join 不起作用

Hibernate FetchMode = Join doesn't work

我看到即使使用 FetchMode=JOIN,Hibernate 也会触发多个查询

下面是我的实体类

 @Entity
 @Table(name = "person")
 public class PersonJPA{
  @Id
  @Column(name = "person_id")
  @GeneratedValue
  private Long personId;

  @OneToMany(mappedBy = "personId",cascade=CascadeType.ALL)
  @Fetch(value = FetchMode.JOIN)
  private Set<AddressJPA> address;
  ......
 }

 @Table(name = "address")
 public class AddressJPA {

  @Id
  @Column(name = "address_id")
  @GeneratedValue
  private long addressId;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "person_id")
  private PersonJPA personId;

 }

我如何编写 JPA CriteriaQuery 来为给定的 personId 选择带有 AddressJPA 列表的 PersonJAP?

是否要检索给定人员 ID 的 PersonJPA 对象,以便同时加载其关联的 AddressJPA 集合?在这种情况下,您需要一个 FETCH JOIN。

在条件 API 中:

EntityManager em = entityManagerFactory.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<PersonJPA> query = cb .createQuery(PersonJPA.class);
Root<PersonJPA> person = query.from(PersonJPA.class);
query.fetch("address");
query.select(person);
ParameterExpression<Long> p = cb.parameter(Long.class);
query.where(cb.equal(cb.get("personId"), p));

JP QL:

SELECT p FROM PersonJPA p JOIN FETCH p.address
WHERE p.personId = :p

或者,您可能希望在注释中指定获取模式 (EAGER)(因为默认情况下关联的集合是延迟加载的):

@OneToMany(mappedBy = "personId",cascade=CascadeType.ALL, fetch=FetchType.EAGER)
private Set<AddressJPA> address;

@Fetch 注释是特定于 Hibernate 的,而不是来自 JPA。它指定了如何获取数据的策略。 查看更多信息 here