簡體   English   中英

如何通過 Hibernate 中具有不同名稱的非 PK 列 map 2 個表

[英]How to map 2 tables through non-PK columns with different names in Hibernate

我有 2 個表,它們可能通過非 PK 輔助列相互關聯。 此外,此匹配的列名在每個表中都不同。 那是,

@Entity
@Table(name = "PLANS_T")
public class Plans {
    private Integer id; // PK
    //...
    private String secondaryIdentifier; // Should be matched with TRAINEES.auxiliaryIdentifier
    //...
}

@Entity
@Table(name = "TRAINEES_T")
public class Trainee {    
    private Integer id; // PK
    //...
    private String auxiliaryIdentifier; // Should be matched with PLANS.secondaryIdentifier
}

PLANSTRAINEE之間的關系是多對一的:您可以為受訓者制定多個計划。

我需要正確注釋這些以指示PLANS_T.secondaryIdentifier應與TRAINEES_T.auxiliaryIdentifier一起用於JOIN (例如在標准 API 中,它需要從一個表到另一個表的連接路徑)。

但我不能使用典型的例子,例如

@Entity
class Trainee {

    @OneToMany(mappedBy = "plan")
    private Collection<Plans> plans = new ArrayList<Plans>();

}

@Entity
class Plans {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="auxiliary_identifier") // Where do I specify "secondaryIdentifier", a non-PK column?
    private Trainee trainee;

}

我需要一種方法來指定注釋中的兩個非 PK 列。 使用 Criteria API 時,這些注釋提供了創建 Join 路徑的路徑。

您應該通過以下方式更正您的映射:

@Entity
class Trainee {

   @OneToMany(mappedBy = "trainee")
   private List<Plans> plans = new ArrayList<Plans>();
}

@Entity
class Plans {

   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name="secondary_identifier", referencedColumnName = "auxiliary_identifier")
   private Trainee trainee;

}
  1. @OneToManymappedBy是擁有關系的字段的名稱。 這是Plans實體的trainee字段。

  2. @JoinColumnreferencedColumnName是該外鍵列引用的列的名稱。

暫無
暫無

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

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