我在这里面临一个小问题。
我有两个实体:Parent和Child,Parent有一个注释@OneToMany。
问题是当我尝试插入一个新的Parent时,它会在持久化子代时崩溃,因为尚未生成父ID。
这是一个解决方法吗?
@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;
}
我认为如果我先坚持父母,坚持孩子将是一个糟糕的方法。
这是一种在坚持父母的情况下坚持孩子的方法吗?
谢谢!
Guys,持久化Parent时发生的异常是: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:列'ID_PRODUTO'不能为空
我发现一个人面临同样的问题:@OneToMany and composite primary keys?(可能会更好地解释)
这是我的插入代码
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
答案 0 :(得分:0)
您的实体类几乎没有问题。
在子实体中,不需要以下字段。
@Id
@Column(name =“ID_PRODUTO”,nullable = true)
private Integer parentId;
更新的实体就是这样。
@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 = "parent", 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", nullable = true)
private Integer parentId; */ // Not required.
@Id
@Column(name = "TAMANHO")
private String tamanho;
@ManyToOne
@JoinColumn(name = "ID_PRODUTO", insertable = false, updatable = false)
private Parent parent;
}
另外,我不了解主键的子内部类。使用正确的主要内容,因为您使用了父级。
插入时将父母和子女的父母都设置为父母。有关详细信息,请参阅我的博客。Here