【发布时间】:2020-12-29 17:52:52
【问题描述】:
我正在尝试通过 freemarker 将孩子添加到预先存在的父母中。但每次我尝试时,我都会收到以下错误:
org.postgresql.util.PSQLException: ERROR: insert or update on table "CHILD TABLE" violates foreign key constraint "KEY" Detail: Key (id)=(WRONG NUMBER) is not present in table "PARENT TABLE".
我似乎每次都按顺序给出一个新的父 ID,而不是在调用 childRepository.save(child); 之前给出并存在于子对象中的父 ID。
代码sn-ps:
家长:
@Entity
@Table(name = "parent")
@EntityListeners(AuditingEntityListener.class)
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@OneToMany(mappedBy = "parent")
private Set<Child> children = new HashSet<Child>();
孩子:
@Entity
@Table(name = "child")
@EntityListeners(AuditingEntityListener.class)
public class Child{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@ManyToOne
@JoinColumn(name = "parent_id", nullable = false)
private Parent parent;
Freemarker 控制器:
@Autowired
private ChildRepository childRepository;
@RequestMapping("/addchild/{id}")
public String addChild(Model model, @PathVariable(value = "id") Long parentId) {
String method = "addChild";
Utils.log(method, "started");
parent parent= parentRepository.findById(parentId)
.orElseThrow(() -> new IllegalArgumentException("parent " + parentId + " not found"));
Utils.log(method, "loaded " + parent);
child child = new child();
child.setparent(parent);
model.addAttribute("child", child);
return "child";
}
@PostMapping("/savechild")
public String savechild(Model model, child child) {
String method = "savechild";
Utils.log(method, "started");
child.getparent().addchild(child);
child = childRepository.save(child);
Utils.log(method, "saved " + child);
return "redirect:/parent/" + child.getparent().getId();
}
【问题讨论】:
-
I'm trying to add children to a pre-existing parent.- 请展示你是如何尝试的。 -
@SternK 我添加了一些处理 freemarker 页面的相关代码
标签: java hibernate hibernate-onetomany