Hibernate one-to-many 双向连接在从 child 保存时提供新的 parent

Hibernate one-to-many bidirectional connection gives new parent when saving from child

我正在尝试通过 freemarker 添加 children 到 pre-existing parent。但每次尝试时,我都会收到以下错误:

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".

我似乎每次都按顺序给出一个新的parent id,而不是在child object之前给出和出现的parent id 17=] 被调用。

代码片段:

Parent:

@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>();

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();
    }

我没有使用过 Freemarker,但 PostMapping 代码对我来说看起来像 Spring MVC 控制器,其中包含基于误解的错误代码。看,PostMapping 从例如获取一些输入一个HTML表单,并构造一个子实例,所有字段根据表单输入设置。

但是由于 HTTP 是一种无状态协议,控制器方法除了您输入的信息之外什么也不知道,并且您之前 GET 调用的父信息完全丢失了。因此,要在 POST 上添加子项,您还必须首先获取父项。

我本以为会看到那样的东西

@Autowired private ParentRepository parentRepository;
@Autowired private ChildrenRepository childrenRepository;

@RequestMapping("/parents/{parentId}/children/{childId}")
public String getChild(Model model, @PathVariable(value = "parentId") Long parentId, @PathVariable(value = "childId") Long childId) {

    // Fetch a specific child for a specific parent fully determined by URL
    Child child = childrenRepository.findByParentIdAndId(parentId, childId).orElseThrow(() -> new IllegalArgumentException("parent " + parentId + "child " + childId + " not found"));
   
    model.addAttribute("child", child);
    return "child";
}

// The parent to add to is referenced by its url, the child constructed by form data
@PostMapping("/parents/{id}")
public String saveChild(Model model, @PathVariable(value = "id") Long parentId, child child) {
    // Fetch the parent you want to add a child to
    parent parent = parentRepository.findById(parentId)
            .orElseThrow(() -> new IllegalArgumentException("parent " + parentId + " not found"));
    // Add the child constructed from form data and send to parent specific url
    parent.addchild(child);
    // Save parent with updated list of children
    parentRepository.save(parent)
    //
    return "redirect:/parents/" + parent.getId();
}

错误是一个错误的约束,可能是早期版本代码的产物