簡體   English   中英

Hibernate批注映射到使用組合鍵的聯接表

[英]Hibernate annotation mapping to joined table with composite key

我有一個實體,我想將OneToOne與帶有復合鍵的表(省略getter / setter)結合在一起:

@Entity
@Table(name = "parent")
public class Parent {
  @Id
  private String parentId;
  @Column(name = "data")
  private String data;
  @OneToOne
  private Child child;
}

和:

@Entity
@IdClass(ChildKey.class)
@Table(name = "child")
public class Child{
  @Id
  private String parentId;
  @Id
  private String username;
  @Column(name = "data")
  private String childData;
}

public class ChildKey implements Serializable {
  private String parentId;
  private String username;
}

父級在子級實體中沒有“用戶名”字段的概念。 我需要將此作為標准。 在數據庫中,child的主鍵位於parentId和username上。

如果我未指定JoinColumn,則休眠狀態將嘗試使用child_username和child_parentId字段進行映射。 如果僅指定一個Joincolumn,則會得到一個損壞的映射。 如果我同時指定了兩個JoinColumns,則在父級上沒有要指定的列。

如何映射該類並將用戶名作為條件傳遞? (它來自身份驗證數據),或者如果我偏離軌道,該如何以其他方式執行此操作。

您也許可以使用派生身份。

Parent類將保持不變; 但您需要指定一個@OneToOne映射回孩子的父對象, ChildChildKey類如下所示:

@Entity
@IdClass(ChildKey.class)
@Table(name = "child")
public class Child{
  @Id
  @OneToOne(mappedBy="child")
  private Parent parent;
  @Id
  private String username;
  @Column(name = "data")
  private String childData;
}

public class ChildKey implements Serializable {
  private String parent; // name matches name of the @Id field and type matches type of Parent @Id field
  private String username; // name and type match those of the @Id field
}

派生身份將在JPA 2.1規范的第2.4.1節中討論。

我最終要做的是在Child類上定義一個@Filter,如下所示:

@Entity
@IdClass(ChildKey.class)
@Table(name = "child")
@FilterDef(name = "usernameFilter", parameters = {
        @ParamDef( name = "username", type="string")
})
public class Child { ... }

在Parent類上,我通過引用過濾器對集合進行了注釋:

@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "parentId")
@Filter(name="usernameFilter", condition = "username = :username")
private List<Child> children;

最后,在我的DAO中,我按名稱對過濾器進行了參數設置,如下所示:

Filter filter = currentSession().enableFilter("usernameFilter");
filter.setParameter("username", user.getUsername());

這樣做產生了我想到的確切的SQL,這是JOIN標准中的一個帶有變量的附加子句:

SELECT 
    ...
FROM
    parent this_
        LEFT OUTER JOIN
    child child_ ON this_.parentId = child_.parentId
        AND child_.username = ?

對於最初的問題,我可能一直不清楚最終的結果。 發布此答案,以防其他人受益。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM