2014-03-26 16 views
0

我試圖找到一種方法來管理一個輕量級時尚有OneToMany關係但永遠不會持久的兩個模型。在沒有數據庫的java中管理一個簡單的OneToMany實體關係

我的搜索引導我到javax.persistence似乎能夠做我想做的,但我似乎無法使其工作。

隨着測試總是說比演講多得多,這是我想達到的目標:

public void test_relationship() { 
    Parent p = new Parent("Mary"); 
    Child c1 = new Child("Hugo"); 
    Child c2 = new Child("Charly"); 
    Child c3 = new Child("Françine"); 

    p.addChild(c1) 
    Assert.assertEquals(p, c1.getParent()); 
    p.removeChild(c1) 
    Assert.assertNull(c1.getParent()); 

    p.addChildren(c1, c2) 
    Assert.assertEquals(p, c1.getParent()); 
    Assert.assertEquals(p, c2.getParent()); 

    c1.removeParent(); 
    Assert.assertFalse(p.hasChild(c1)); 

    c1.setParent(p); 
    Assert.assertTrue(p.hasChild(c1)); 
} 

所有這一切都沒有數據庫。唯一的目的是促進從一個對象訪問另一個對象。這些對象將根據作爲HTTP請求負載(JSON格式)接收到的數據進行構建,並且需要作爲響應的一部分序列化回JSON。

現在這裏是我做了什麼

@Entity 
public class Parent implements Serializable { 

    private Collection<Child> children = new HashSet<Child>(); 

    @Id 
    private String    id; 

    @OneToMany(mappedBy = "parent", fetch = FetchType.EAGER) 
    public Collection<Child> getChildren() { 
     return children; 
    } 

    public void addChild(child) { 
     this.children.add(child); 
    } 

    public void removeChild(child) { 
     this.children.remove(child); 
    } 

    public boolean hasChild(child) { 
     this.children.contains(child); 
    } 
} 

@Entity 
public class Child implements Serializable { 
    private Parent parent; 

    @Id 
    private String id; 

    @ManyToOne 
    public Parent getParent() { 
     return parent; 
    } 

    public void setParent(Parent parent) { 
     this.parent = parent; 
    } 

    public void removeParent() { 
     this.parent = null; 
    } 
} 

編輯: 我期待的關係行爲來自javax.persistence。也許通過EntityManager?我真的很困惑這些工作。我知道我可以自己編寫這個行爲,但是我想避免在每個實體的每個關係上都這樣做,並且可能會得到最乾淨的代碼。

+0

如果你永遠也不會向他們堅持到關係數據庫,何苦對待他們像關係型數據庫實體在第一位?爲什麼不使用常規的對象圖? –

+0

@MikkelLøkke我不確定什麼是對象圖,但我想要的是大多數ORM在管理關係時給予的安慰。例如如果我向孩子添加一個孩子,那麼父母在孩子中被引用,反之亦然。如果你有另一種解決方案,不涉及爲每個關係編碼,我會採取它:) – Crystark

+0

對象圖基本上是你已經有。兒童的HashSet,這是OneToMany關係的對象版本。問題是你需要在另一個方向上做。如斯蒂芬斯的回答指出的那樣,這很快就會變成簿記地獄,至少如果你使用複雜的數據集。根據我的經驗,最簡單的方法是使用Guava的BiMap系列。它需要重新設計你已有的東西,但與IMHO一起工作要容易得多。 https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap –

回答

0

你是那裏的一部分。缺少的是當你創建/更新/刪除父母的一方< - >孩子關係時,你需要在另一方做同樣的事情。

因此,例如

public void setParent(Parent parent) { 
    if (this.parent != null) { 
     this.parent.removeChild(this); 
    } 
    this.parent = parent; 
    parent.addChild(this); 
} 

(並更改childschildren或語法怪物會吃了你!)

+0

我有點料到這是由@ @ OneToMany魔術完成的。這是我使用'javax.persistence'的唯一原因:不需要自己管理每個關係。 – Crystark

+0

那麼,我沒有意識到沒有做持久性的任何javax.persistence實現... –

相關問題