gpt4 book ai didi

java - 如何更新一对一关系表?

转载 作者:太空宇宙 更新时间:2023-11-04 09:55:15 24 4
gpt4 key购买 nike

我想知道如何通过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

最佳答案

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

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

应该是:

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

If the relationship is bidirectional, the non-owning side must use the mappedBy element of the OneToOne annotation to specify the relationship field or property of the owning side

Oracle Docs

关于java - 如何更新一对一关系表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54233632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com