hibernate一对多双向连接在从子级保存时提供新的父级

mefy6pfw  于 2021-06-27  发布在  Java
关注(0)|答案(2)|浏览(321)

我正在尝试通过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,而不是之前在子对象中给出并显示的父id childRepository.save(child); 被称为。
代码段:
起源:

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

owfi6suc1#

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

fhg3lkii

fhg3lkii2#

我没有使用freemarker,但是postmapping代码在我看来像是一个springmvc控制器,它包含基于误解的错误代码。请参阅,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();
}

相关问题