2010-12-21 48 views
7

我有兩個實體:休眠插入級聯不插入外鍵

@Entity 
public class File 
....... 
@Id @GeneratedValue(strategy=GenerationType.AUTO) 
private int id; 
@OneToMany(fetch=FetchType.LAZY, mappedBy="file", cascade=CascadeType.ALL) 
private List<Tag> tags; 
....... 
OTHER PROPERTIES 
....... 

@Entity 
public class Tag 
....... 
@Id @GeneratedValue(strategy=GenerationType.AUTO) 
private int id; 
@ManyToOne 
@JoinColumn(name="file_id") 
private File file; 
@Column 
private String tag; 
....... 
OTHER PROPERTIES 
....... 

我試圖做插入到文件(以及隨後TAG)以下:

File file = new File(); 
Tag tag = new Tag(); 
tag.setTag("tag1"); 
Tag2 tag2 = new Tag(); 
tag2.setTag("tag2"); 
List<Tag> tags = new ArrayList<Tag>(); 
tags.add(tag); 
tags.add(tag2); 
file.setTags(tags); 
---Add other file attributes here--- 

我然後插入用我的DAO文件:

sessionFactory.getCurrentSession().saveOrUpdate(file); 

在我的日誌我看到一個插入到我的「文件」表2個鑲入我的標籤表,但是,我的標記表中指向我的文件表(file_id)的外鍵是NULL。

我可能會做錯什麼?

回答

13

您未設置標籤文件,只是將標籤設置爲文件。請記住,在OOP中,與關係模型相反,您必須設置關係的兩端。您不能僅僅因爲您將一組標籤添加到文件而從標籤導航到文件。就你而言,你可以從文件導航到標籤(即:列出文件的所有標籤)。通過僅查看標籤,您無法確定標籤屬於哪個文件。

什麼通常做的是在模型的一個一個輔助方法,如:

public void addTag(Tag tag) { 
    this.tags.add(tag); 
    tag.setFile(this); 
} 

this爲例(從Hibernate的測試套件):

+1

謝謝,這個工作。由於某種原因,我確實認爲Hibernate會爲我假設我希望它被Tag更新爲我的文件,因爲我有雙方註釋的關係。 – 2010-12-21 15:53:00

+0

該鏈接不存在更多:(你可以提供其他來源? – Filipe 2014-02-20 21:30:03

+0

我已經改變了答案,指向最新版本。 – jpkrohling 2014-02-21 08:03:32

3

數據庫中的外鍵反映的是Tag.file的狀態(因爲Tag在雙向多對一關係中是關係的「多邊」)。

我看不到您設置的位置。