Note that there are some explanatory texts on larger screens.

plurals
  1. POIn JPA, having a many-to-one as primary key throws referential integrity constraint violation
    primarykey
    data
    text
    <p>I have defined the following entities:</p> <pre><code>@Entity public class Child implements Serializable { @Id @ManyToOne(cascade = CascadeType.ALL) public Parent parent; @Id public int id; } @Entity public class Parent { @Id public int id; } </code></pre> <p>When I try to persist a Child with the following code:</p> <pre><code>Parent p = new Parent(); p.id = 1; Child c1 = new Child(); c1.id = 1; c1.parent = p; em.persist(c1); </code></pre> <p>Hibernate throws a 'Referential integrity constraint violation' error:</p> <pre><code>Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FK3E104FC802AAC0A: PUBLIC.CHILD FOREIGN KEY(PARENT_ID) REFERENCES PUBLIC.PARENT(ID) (1)"; SQL statement: insert into Child (parent_id, id) values (?, ?) [23506-171] </code></pre> <p>I believe this is because it first inserts the Child and then the Parent, while I would expect it to insert the Parent first. Any idea how I can change the order of insertion, or how to to solve this in some other way?</p> <p>Update: note that this approach is not JPA compliant, but uses Hibernate specifics (see section <strong>5.1.2.1. Composite identifier</strong> in the <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#mapping-declaration-id" rel="nofollow">hibernate docs</a>)</p> <p>Update: I would like to only have to persist the Child c1 and have the persist cascade to Parent p automatically (this update is in reaction to @Alf's answer below).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload