JPA /Hibernate - 如何在实体上定义自定义连接子句?

JPA /Hibernate - How to define custom join clause on entity?

我想将多个表连接到一个列,并通过常量值附加条件。像这样:

@Entity
public class User {
  @Id
  private String id;
  ...
}

@Entity
public class Group {
  @Id
  private String id;
  ...
}

@Entity
public class Resource {
  @Id
  private String id;
  
  private String targetId;

  private String tatgetType;
  
  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "targetId", referencedColumnName = "id", 
    insertable = false, updatable = false)
  // @WhereJoinTable(clause = "target_type = 'USER'")  // just apply for collection
  private User targetUser;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "targetId", referencedColumnName = "id", 
    insertable = false, updatable = false)
   // @WhereJoinTable(clause = "target_type = 'GROUP'") // just apply for collection
  private Group targetGroup;
  ...
}

不幸的是'@WhereJoinTable'刚刚申请collection。

我也尝试“@JoinFormula”,但它需要 referencedColumnName

我可以用 JPA 实现这个场景吗?

最后我找到了一个技巧,虽然不是标准但很管用。

@ManyToOne(fetch = FetchType.LAZY)
@JoinFormula(value = "(SELECT target_id WHERE target_type = 'USER')", 
    referencedColumnName = "id")
private User targetUser;