JPA @OneToMany -> Parent - Child Reference (Foreign Key)

后端 未结 5 1829
太阳男子
太阳男子 2020-12-07 19:10

i have a Question about referencing ParentEntities from Child Entites ir If i have something like this:

Parent.java:

@Entity(name ="Parent")
         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 19:17

    We ran into a problem while persisting a simple object graph like the one shown above. Running in H2 everything would work, but when we ran against MySQL the "paren_id" in the child table (defined in the @JoinColumn annotation) wasn't getting populated with the generated id of the parent - even though it was set as a non-null column with a foreign key constraint in the DB.

    We'd get an exception like this:

    org.hibernate.exception.GenericJDBCException: Field 'paren_id' doesn't have a default value
    

    For anyone else who might run into this, what we eventually found was that we had to another attribute to the @JoinColumn to get it to work:

    @JoinColumn(name="paren_id", nullable=false)
    

提交回复
热议问题