Search code examples
javahibernatehibernate-onetomany

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


I'm trying to add children to a pre-existing parent via freemarker. But every time I try, I get the following error:

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

I seems to give a new parent id sequentially every time, instead of the parent id that is given and present in the child object before childRepository.save(child); is called.

Code snippets:

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 Controller:

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

Solution

  • The error was a mistaken constraint, presumably an artifact from an earlier version of the code