Hibernate and H2 “Referential integrity constraint violation” for OneToMany bidirectional mapping

后端 未结 1 1178
南笙
南笙 2021-02-18 19:41

So I have two simple beans -- FatKid and Hamburgers. Now, for reasons unbeknownst to me I need to be able to not only look up all of the hamburgers someone ate, but also who at

相关标签:
1条回答
  • 2021-02-18 20:21

    Your mappings look weird to me. You have a @JoinColumn in both sides of the relationship, each pointing to the primary key of the other table. That doesn't seem to be a OneToMany relationship.

    Your OneToMany should tell the owner of the relationship:

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "whoDoneAteMe")
    public List<Hamburger> getHamburgers() {
        return hamburgers;
    }
    

    and then in the other side:

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "fatkid_id")
    public FatKid getWhoDoneAteMe() {
        return whoDoneAteMe;
    }
    

    You might be able to optimize your code further too. As your FatKid objects are aware of the Hamburger objects and you have configured cascading, you could do:

        session.beginTransaction();
        FatKid fk = new FatKid();
        fk.setName("Darrell");
    
        Hamburger hamburger_1 = new Hamburger();
        hamburger_1.setDescription("Juicy quarter pounder with cheese");
        hamburger_1.setWhoDoneAteMe(fk);
        fk.getHamburgers().add(hamburger1);
    
        Hamburger hamburger_2 = new Hamburger();
        hamburger_2.setDescription("Ground buffalo burger topped with bacon and a sunny-side egg");
        hamburger_2.setWhoDoneAteMe(fk);
        fk.getHamburgers().add(hamburger2);
    
        session.save(fk);
        session.getTransaction().commit();
    
        sessionFactory.close();
    

    The above code should save the complete object graph with just one commit operation and in a single transaction.

    0 讨论(0)
提交回复
热议问题