[英]Hibernate validating wrong entity foreign key
當Hibernate的EntityManager啟動並驗證實體的映射時,我遇到了一個問題。 用我能起草的最簡單的術語,我有以下四個類:
@Entity
@Table(name="abc_rule")
public class Rule {
@Id
@Column(name="id")
private Integer id;
@ManyToOne
private RuleType ruleType;
}
@Entity
@Table(name="abc_rule_type")
@IdClass(RuleTypeKey.class)
public class RuleType {
@Id
private String typeCode;
@Id
private String otherCode;
@Column(name="descr")
private String description;
}
public class RuleTypeKey {
@Id
@Column(name="type_cd")
private String typeCode;
@Id
@Column(name="other_cd")
private String otherCode;
}
@Entity
@Table(name="abc_rule_type")
public class RuleTypeSimple {
@Id
@Column(name="id")
private Integer id;
@Column(name="type_cd")
private String typeCode;
@Column(name="other_cd")
private String otherCode;
@Column(name="descr")
private String description;
}
Hibernate啟動時,出現以下異常:
外鍵(FK4AD4C4B924F958E2:abc_rule [ruleType_type_cd,ruleType_other_cd])的列數必須與引用的主鍵(abc_rule_type [id])
如果我暫時命名的注解@Table RuleTypeSimple
是"abc_rule_type_123"
,則Hibernate驗證並使用映射預期。 對我來說,這似乎是Hibernate根據表名而不是根據所引用的實際類的設置來驗證外鍵映射。
有什么明顯的我想念的東西會迫使Hibernate基於類進行驗證嗎? 還是讓它甚至不驗證外鍵,而只是相信我做對了?
附帶說明一下,我知道並沒有很好的理由使用兩個不同的標識符設置將類映射兩次。 在我的情況下,這是由於作用在同一數據庫上的兩個不同代碼項目的合並引起的。 一個以只讀方式使用,因此可以擺脫這種異常的映射。 不幸的是,這兩個代碼庫都在其類的版本周圍包裹了大量代碼,重構將是一項艱巨的任務,我希望目前可以避免。
請記住,Hibernate是一個ORM工具,因此,您應該通過遵循一些OOP規則或最佳實踐來嘗試利用它。
根本不應該使用幾列作為主鍵,並且如果您完全被迫這樣做(例如,如果有人要殺死您,或者您沒有這樣做,或者您已經創建了一個古老的Relational數據庫並且不在您的人類手下)限制),則應使用@EmbeddedId注釋的@Embedable Id,也不要使用@Id注釋對每列進行注釋 。
這是一個EmbeddedId示例: EmbeddedCompoundPrimaryKey示例
同時,我不確定要創建的模型是什么(至少如果發布圖表或表格腳本會有所幫助),但是經過此更正,它不會給您帶來更多錯誤:
@Entity
@Table(name="abc_rule")
public class Rule {
@Id
@Column(name="id")
private Integer id;
@ManyToOne
private RuleType ruleType;
}
@Entity
@Table(name="abc_rule_type")
//@IdClass(RuleTypeKey.class) <--I don't think this is right
public class RuleType {
@EmbeddedId //Add this
private RuleTypeKey id; //And this
/* Remove this
@Id
private String typeCode;
@Id
private String otherCode;*/
@Column(name="descr")
private String description;
}
@Embeddable //Add this
public class RuleTypeKey {
//@Id <--remove this
@Column(name="type_cd")
private String typeCode;
//@Id <--remove this
@Column(name="other_cd")
private String otherCode;
}
@Entity
//@Table(name="abc_rule_type") <--must be different table name
@Table(name="abc_rule_type_simple")
public class RuleTypeSimple {
@Id
@Column(name="id")
private Integer id;
@Column(name="type_cd") //Are this two colums a reference to
private String typeCode; //The RuleType too?? if so the must be
//The same as in class Rule (ManyToOne)
@Column(name="other_cd")
private String otherCode;
@Column(name="descr")
private String description;
}
試試看,讓我知道它是否有效(它可能有一些sintax錯誤,請檢查一下)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.