In JPA, having a many-to-one as primary key throws referential integrity constraint violation

痞子三分冷 提交于 2019-12-08 19:04:27
em.persist(p);
em.persist(c1);

UPDATE

I think the problem is that your code is not JPA compliant. Try with embeddedId, it works for me.

@Embeddable
public class ChildPK implements Serializable {
    private int parentId;

    private int childId;

    // getters and setters
}

@Entity
public class Child implements Serializable {
    @EmbeddedId
    public ChildPK id = new ChildPK();

    @MapsId( "parentId" )
    @ManyToOne
    public Parent parent;

}


    Parent p = new Parent();
    p.id = 1;

    Child c1 = new Child();
    c1.id.setChildId( 1 );

    c1.parent = p;

    em.persist( c1 );

I think it works with @IdClass too, but I never used it.

I think you are right at your point.

You first need to persist the child then parent.

Barry

A ManyToOne relationship in Java is where the source object has an attribute that references another target object and (if) that target object had the inverse relationship back to the source object it would be a OneToMany relationship.

JPA also defines a OneToOne relationship, which is similar to a ManyToOne relationship except that the inverse relationship (if it were defined) is a OneToOne relationship

The main difference between a OneToOne and a ManyToOne relationship in JPA is that a ManyToOne always contains a foreign key from the source object's table to the target object's table, where as a OneToOne relationship the foreign key may either be in the source object's table or the target object's table.

you can see below example

@Entity
public class Student {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="DEPT_ID")
private Department department;

 //getter and setter
}

@Entity
public class Department {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
 //getter and setter

}


Student student = new Student();
student.setName("prateek");
em.persist(student);


Department dept = new Department();
dept.setName("MCA KIIT");
student.setDepartment(dept);
em.flush();

I come with what is, I guess, a simpler solution:

@Entity
public class Child implements Serializable {
    @Id
    @JoinColumn(name = "id")
    private String id;

    @ManyToOne
    @PrimaryKeyJoinColumn
    private Parent parent;

    private String otherMember;    
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!