我正在使用Hibernate 4(使用Spring)将我的对象持久化到数据库中。 当我尝试使用集合子集保存父级时,我遇到了一些问题。
我的表:
| A | => PK (Composite) [String + Integer]
| B | => PK (Composite) [Stirng + Integer] + Integer
自然地,B的PK与A的相同PK复合,A含有B的集合。
在我想要的代码中:
A parent = new A();
parent.addCollection(new B());
parentDao.create(parent)
当Hibernate持久化对象时,它可以将String设置为A PK并计算Inter的max + 1。 B PK的方式相同,Hibernate从A(parent => child)设置相同的PK值,并为第二个Intenger计算max + 1.
有可能吗? 提前致谢
修改
我的班级:
Class A {
static Class A_PK {
private String codAzienda;
private Integer year;
... Get, Set, HashCode, Equals and toString() ...
}
private A_PK id;
... another columns ...
@OneToMany(cascade=ALL)
@JoinColumns({
@JoinColumn(name="cod_azienda"),
@JoinColumn(name="year")
})
List<B> children;
}
Class B {
static Class B_PK {
private String codAzienda;
private Integer year;
private Integer nextId;
... Get, Set, HashCode, Equals and toString() ...
}
@EmbeddedId
@AttributeOverrides({
@AttributeOverride(name = "codAzienda", column = @Column(name = "cod_azienda")),
@AttributeOverride(name = "codCliente", column = @Column(name = "cod_cliente"))
})
private B_PK id;
... another columns ...
}
答案 0 :(得分:1)
尝试以下方法:
<强> A.java 强>
@Entity
@Table(name = "TABLE_A")
public class A implements Serializable {
@Id
@Column(name = "STR_ID")
private String strId;
@Id
@Column(name = "INT_ID")
@GeneratedValue(strategy = GenerationType.TABLE)
private Integer intId;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "a")
private List<B> bs;
public A(String strId) {
this.strId = strId;
}
public void addB(B b) {
if (bs == null) {
bs = new ArrayList<B>();
}
b.setA(this);
bs.add(b);
}
}
<强> B.java 强>
@Entity
@Table(name = "TABLE_B")
public class B implements Serializable {
@Id
@Column(name = "INT_ID")
@GeneratedValue(strategy = GenerationType.TABLE)
private Integer intId;
@Id
@ManyToOne
@JoinColumns({
@JoinColumn(name = "A_STR_FK", referencedColumnName = "STR_ID"),
@JoinColumn(name = "A_INT_FK", referencedColumnName = "INT_ID")
})
private A a;
void setA(A a) {
this.a = a;
}
}