【问题标题】:JPA /Hibernate - How to define custom join clause on entity?JPA /Hibernate - 如何在实体上定义自定义连接子句?
【发布时间】:2021-09-21 07:13:03
【问题描述】:

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

@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'刚刚申请领取。

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

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

【问题讨论】:

    标签: java hibernate join jpa-2.0


    【解决方案1】:

    最后我找到了一个技巧,虽然不标准,但很有效。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多