简体   繁体   中英

JPA/Hibernate using shared id and cascade=all tries to save child before parent, causing foreign key violation

I am using JPA with hibernate. I have a 1-to-1 parent child relationship (the child is optional), with the id shared between the two and a foreign key relationship on the child table. My entities look like this:

parent:

public class LogItemEntity {
...

    @OneToOne(cascade={CascadeType.ALL}, mappedBy = "logItem", orphanRemoval=true, optional=true)
    @PrimaryKeyJoinColumn(referencedColumnName="ral_id")
    private LogAdditionalRequirement additionalRequirement;
...
}

child:

public class LogAdditionalRequirement {
...
    @Id
    @GeneratedValue(generator = "foreign")
    @GenericGenerator(name = "foreign", strategy = "foreign", parameters = { @Parameter(name = "property", value = "logItem") })
    @Column(name = "ral_id")
    private Long id;

    @OneToOne(optional=false)
    @PrimaryKeyJoinColumn(referencedColumnName="id")
    private LogItemEntity logItem;
...
}

When inserting a new object, the id for the parent is generated from a sequence and the cascade operation copies it onto the child. But the sql insert for the child is placed in the action queue of the session before the sql insert for the parent, and so it fails with a constraint violation on the foreign key:

ERROR o.h.util.JDBCExceptionReporter - ERROR: insert or update on table "rar_log_additional_requirement" violates foreign key constraint "fk_rar_ral_id"
Detail: Key (ral_id)=(70150) is not present in table "ral_log".

So how can I make the insert of the parent happen first?

This must be a pretty common usage, so I assume I'm doing something wrong, but I don't see what it is. I originally had the mappedBy attribute on the child side. I think that's wrong, but swapping it round made no difference.

One solution could be to remove the cascade "cascade={CascadeType.ALL}"

More on this subject here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM