2017-04-01 75 views
1

我有一個Spring Boot/Spring Data的問題,我只能在一個方向上創建嵌套實體。Spring Data Rest - 只能在一個方向創建嵌套實體

我有兩個實體,父和子,父母與子實體具有OnetoMany關係。

如果我創建了一個孩子,這樣做:

POST http://localhost:8080/children 
{ 
    "name": "Tenzin" 
} 

,然後做這個創建父:

POST http://localhost:8080/parents 
{ 
    "name": "Fred and Alma", 
    "children": [ "http://localhost:8080/children/1" ] 
} 

這是行不通的。

然而,如果我先創建父,然後做這個創建一個新的孩子,它的工作:

POST http://localhost:8080/children 
{ 
    "name": "Jacob", 
    "parent": [ "http://localhost:8080/parents/1" ] 
} 

爲什麼是這種情況,這是預期的行爲,還是我做錯了什麼?

是因爲父實體(見下文)在子屬性上有cascade = ALL?

父實體:

@Entity 
public class Parent { 
    @Id 
    @GeneratedValue(strategy=GenerationType.IDENTITY) 
    private Long id; 

    @OneToMany(mappedBy="parent", cascade = CascadeType.ALL) 
    private List<Child> children = new ArrayList<>(); 

    private String name; 

    public Long getId() { 
     return id; 
    } 

    public void setId(Long id) { 
     this.id = id; 
    } 

    public List<Child> getChildren() { 
     return children; 
    } 

    public void setChildren(List<Child> children) { 
     this.children = children; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 
} 

實體Child:

@Entity 
public class Child { 
    @Id 
    @GeneratedValue(strategy=GenerationType.IDENTITY) 
    private Long id; 

    private String name; 

    @ManyToOne 
    private Parent parent; 

    public Long getId() { 
     return id; 
    } 

    public void setId(Long id) { 
     this.id = id; 
    } 

    public Parent getParent() { 
     return parent; 
    } 

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

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 
} 
+0

您可以顯示您的回購協議嗎? – Cepr0

+0

嘿Cepr0,它是:https://github.com/simbro/spring-boot-practice-application - 雖然我想我已經想通了 - 見下文。 – simbro

回答

0

在您例如孩子是relationchip(它保存在數據庫中的子表)的所有者。我認爲存在這個問題。 Spring Data Rest將子對象加載到「子」字段中,但不知道它也應該更改子對象的「父」字段。 (另請參閱https://stackoverflow.com/a/1796501/7226417)。

您可以通過捕獲Spring Data Rest事件(http://docs.spring.io/spring-data/rest/docs/current/reference/html/#events)解決此問題並手動設置「父」字段。

+1

嗨Benkuly,謝謝你的回答,我忽略了vhild是這個關係的所有者的事實。這解釋了正在發生的事情。謝謝你的幫助。 – simbro

0

請參見Benkuly上面的反應,基本上,一個協會必須有一個所有者,這個所有者必須存在以存在任何關係。參考Hibernate文檔:

https://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping-association

的關聯可以是雙向的。在雙向關係中,其中一方(並且只有一方)必須是所有者:所有者負責關聯列更新。要聲明一方不負責關係,使用屬性mappedBy。 mappedBy是指所有者端的關聯的屬性名稱。在我們的情況下,這是護照。正如你所看到的,你不必(不得)聲明連接列,因爲它已經在所有者端聲明。