与Hibernate 5 Core的左侧外部联接

pgpifvop  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(104)

我有两个实体(实体A和实体B),它们之间有一个可选的@ONEtoONE关系。
实体A:

@Setter
@Getter
@NoArgsConstructor
@Entity(name = "EntityA")
public class EntityA {

  @Id
  private Long id;

  @OneToOne(targetEntity = EntityB.class, mappedBy = "entityA", fetch = FetchType.LAZY, cascade = CascadeType.ALL, optional = true)
  private EntityB entityB;

  // other members
}

实体B:

@Setter
@Getter
@NoArgsConstructor
@Entity(name = "EntityB")
public class EntityB {

  @Id
  private Long id;

  @OneToOne(targetEntity = EntityA.class, fetch = FetchType.LAZY)
  @MapsId
  @JoinColumn(name = "id")
  private EntityA entityA;

  @Column(name = "status", nullable = false, unique = false)
  private Short status;

  // other members
}

我要选择与实体B没有任何对应关系的所有实体A,或者如果有对应关系,则实体B的状态应为0。
从普通的SQL中,我认为我的目标是:

SELECT a.*
  FROM EntityA a
  LEFT JOIN EntityB b ON a.id = b.id
  WHERE b.id IS NULL OR b.status = 0

使用Hibernate5Core和PostgreSQL实现这一点的最佳策略是什么?
我的方法是:

getSession().createQuery("SELECT a FROM EntityA a LEFT JOIN a.entityB b " +
                            "WHERE b IS NULL OR b.status = :status", EntityA.class)
                    .setParameter("status", (short) 0);

这是正确的做法吗?
如何在同一查询中急切地获取EntityB实体?
谢谢。

icomxhvb

icomxhvb1#

您的查询看起来是正确的。另外,如果您想要急切地获取EntityB,只需在查询中添加‘FETCH’

createQuery(
    "SELECT a FROM EntityA a " +
    "LEFT JOIN FETCH a.entityB b " +
    "WHERE b IS NULL " +
    "OR b.status = :status", EntityA.class).setParameter("status", (short) 0)

相关问题