Im facing a little problem here.
I have two entities: Parent and Child, Parent has a List annotated @OneToMany.
The problem is when I try to insert a new Parent, it crashes when persisting the children, because the Parent Id was not generated yet.
Is that a fix for it?
@Entity
@Table(name = "PRODUTO")
public class Parent extends BaseEntity
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID_PRODUTO")
private Integer produtoId;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "produtoId", orphanRemoval = true)
// @JoinTable(name = "PRODUTO_TAMANHO", joinColumns = @JoinColumn(name = "ID_PRODUTO"))
@OrderBy("preco ASC")
private List<Child> children;
}
@Entity
@IdClass(Child.PrimaryKey.class)
@Table(name = "PRODUTO_TAMANHO")
public class Child extends BaseEntity
{
public static class PrimaryKey extends BaseEntity
{
private static final long serialVersionUID = -2697749220510151526L;
private Integer parentId;
private String tamanho;
//rest of implementation
}
@Id
@Column(name = "ID_PRODUTO")
private Integer parentId;
@Id
@Column(name = "TAMANHO")
private String tamanho;
@ManyToOne
@JoinColumn(name = "ID_PRODUTO", insertable = false, updatable = false)
private Parent parent;
}
I think if I persist firstly the parent, than persist the children would be a bad approach.
Is that a way to persist the children, when persisting Parent?
Thanks!
Guys, the exception that occurs when persisting Parent is: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'ID_PRODUTO' cannot be null
I found a guy facing the same problem: @OneToMany and composite primary keys? (maybe it's better explained)
Here is my insertion code
Parent parent = new Parent();
Child child1 = new Child();
child1.setTamanho("Tamanho 1");
child1.setParent(parent);
Child child2 = new Child();
child2.setTamanho("Tamanho 1");
child2.setParent(parent);
List<Child> children = parent.getChildren();
children.add(child1);
children.add(child2);
save(parent);
//all of this instances, is coming from a view.jsp binded by spring, I can confirm it is exactly like this, with parentId as null
//when updating, it goes perfectly