2

I have a Parent Entity which has its Id autogenerated. It has a list of child entities whose composite key uses the Parent Entites autogenerated id as a foreign key.

Parent Entity

@Entity
@Table(name = "parent_table")
public class Parent {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;

@OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST)
private List<Child> children;

}

Child Entity

@Entity
@Table(name = "child_table")
public class Child{

@EmbeddedId
private ChildPK pk;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id", insertable = false, updatable = false)
Parent parent;

}

Child PK

@Embeddable
public class ChildPK{

@Column(name = "id", nullable = false)
private Integer id;

@Column(name = "id2", nullable = false)
private Short id2;

@Column(name = "id3", nullable = false)
private Integer id3;

}

Here the composite key for the Child entites uses the Parent keys autogenerated id along with 2 other value.

I populated the Parent entity with all the required values along with the child entities and all its values. Only the id parameter in both parent and child was left null as it has to be autogenerated.

But on executing the create method the Parent entity gets inserted with the generated id but this id is not set into the child entities resulting in a Null column error during insertion of child.

java.sql.SQLException: Cannot insert a null into column (child.id)
Jobin Thomas
  • 75
  • 1
  • 8
  • Most likely cause is that you have not set the parent reference on the child. child.setParent(parent); https://stackoverflow.com/questions/26219099/how-to-persist-two-entities-with-jpa/26220097#26220097 – Alan Hay Feb 27 '18 at 08:54
  • I have the same issue and I have parent and child set but still the child save fails with foreign key constraint. – Divyesh Kalbhor Jul 10 '20 at 05:24

0 Answers0