如何更新一对一关系表?

时间:2019-01-17 10:16:29

标签: java hibernate jpa

我想知道如何通过JPA save()方法完全更新一对一关系表。

我尝试使用JPA save()方法子表将一些数据更新到子表和父表。

然后我期望更新两个表(儿童和父母)。 但是有更新的父表和插入的子表。

// parent Entity
@Entity
public class Parent {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(nullable = false)
    private String title;
    @Column(nullable = false)
    private String content;
    @OneToOne(mappedBy = "parent", cascade = CascadeType.ALL)
    @JoinColumn(name = "parent_id")
    private Children children;
}

// children Entity
public class Children {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(nullabel = false)
    private String picture;
    @OneToOne
    private Parent parent;
}

// Parent Table
id | title | content
1  | "..."| "..."

// Children Table
id | picture  | parent_id
1  | "..."     | 1



// Service
childrenRepository.save(childrenEntity);


// Result 
Updated Parent Tables;
-----------------------
id | title     | content
1  | "updated!"| "updated!"



Inserted Children Tables;
-----------------------
id | picture      | parent_id
1  | "..."        | 1
2  | "inserted!"  | 1     <---- This is not my purpose.




// The below's my purpose it.

Updated Children Tables;
-----------------------
id | picture           | parent_id
1  | "updated!"        | 1

1 个答案:

答案 0 :(得分:0)

您对Children的注释看起来不正确。

@OneToOne(mappedBy = "children", cascade = CascadeType.ALL)
private Children children;

应该是:

@OneToOne(mappedBy = "parent", cascade = CascadeType.ALL)
private Children children;
  

如果关系是双向的,则非所有权方必须使用   OneToOne批注的mappingBy元素,用于指定   拥有方的关系字段或财产

Oracle Docs