[英]Hibernate mapping One class to two tables (the two tables have many to one relationship)
[英]Hibernate one class to many tables
我想知道是否有可能將多個表提取到只有一個java類例如:
TABLE LABELS;
TABLE STANDARDS;
TABLE REFERENCES;
映射到同一個類
public Class Information {
private String type; // the type is the element who have to do the mapping => LABELS/STANDARDS/REFERENCES
...
}
由於技術原因,我不可能為每種類型構建一個類(我知道一些遺產應該很酷)。
謝謝
吉爾斯
編輯:
我會嘗試多一點:)
我正在使用JMS服務來獲取信息。 每條消息都有一個特殊的類型,(在我的例子中:“標簽”,“標准”和“參考”)。
通過使用這些類型,我想在相應的表中持久化信息。 每個消息的結構都完全相同,這就是為什么我想使用一個獨特的POJO。
我希望它更好解釋:)
編輯2:
TABLE LABELS (
ID PRIMARY KEY AUTO_INCREMENT,
MESSAGE VARCHAR(255),
AUTHOR VARCHAR(255)
);
TABLE STANDARDS(
ID PRIMARY KEY AUTO_INCREMENT,
MESSAGE VARCHAR(255),
AUTHOR VARCHAR(255)
);
TABLE REFERENCES (
ID PRIMARY KEY AUTO_INCREMENT,
MESSAGE VARCHAR(255),
AUTHOR VARCHAR(255)
);
這是JMS的一些例子
headers :
type : label
body:
{message:"name of the country",author:"john doe"}
headers :
type : label
body:
{message:"nom du pays",author:"jenny doe"}
headers :
type : reference
body:
{message:"country",author:"john doe"}
我想將它們放入信息類並將它們保存到正確的表中
嘗試這個:
@MappedSuperclass
public class Base {
private String message;
private String autor;
@Column(name = "MESSAGE")
public String getMessage(){
return message;
}
public void setMessage(final String message) {
this.message = message;
}
@Column(name = "AUTOR")
public String getAutor(){
return autor;
}
public void setAutor(final String autor) {
this.autor = autor;
}
}
三個班:
@Entity
@Table(name="LABELS")
public class Labels extends Base{};
和
@Entity
@Table(name="STANDARDS")
public class Standards extends Base{};
和
@Entity
@Table(name="REFERENCES")
public class References extends Base{};
現在,您可以使用以下內容保留數據:
Base b;
if (info.getType().equals("REFERENCES")) {
b=new References();
} else if (info.getType().equals("LABELS")) {
b=new Labels();
} else if (info.getType().equals("STANDARDS")) {
b=new Standards();
} else {
return;
}
b.setMessage(info.getMessage());
b.setAutor(info.getAutor());
Transaction t = session.beginTransaction();
session.persist(b);
t.commit();
您可以使用secondaryTables
:
http://docs.oracle.com/javaee/6/api/javax/persistence/SecondaryTables.html
您可能會問是否可以為每個子類映射執行一個表 。 每個表可以有一個類,但都可以從公共基類繼承。
或者,如果您正在構建只讀映射,則可以在所有相關表上創建一個UNION
視圖,並使用Hibernate映射視圖。 就像是
-- SQL
CREATE VIEW information AS
SELECT 'LABEL' AS type,... FROM labels
UNION
SELECT 'STANDARD',... FROM standards
UNION
SELECT 'REFERENCE',... FROM references
;
/* Java */
@Entity
@Table(name="information")
public class Information {
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.