我有两个表(列): PARENT(P_ID_PK,AUTO_INCREMENT)和 儿童(P_ID_FK,C_NAME(PK = P_ID + C_NAME))
他们有一对多的关系。当我持久保存父对象和子对象时,P_ID_PK具有auto_incremented值,但P_ID_FK仅具有默认值(0)。如何让P_ID_FK具有与P_ID_PK相同的值?这是我的代码:
@Entity
@Tabler (name="PARENT")
public class Parent {
@ID
@Column (name = "P_ID_PK")
@GeneratedValue(strategy=GenerationType.Identity)
private Integer pIdPk;
@OneToMany(mappedBy = "parent", cascade={CascadeType.ALL})
@JoinColumn (name = "P_ID_PK")
private List<Child> children;
//...getters setters, constructors
}
@Embeddable
public class ChildId implements Serializable {
private Integer pIdFk;
private String cName;
@Column(name="P_ID_FK")
public Integer getPIdFk(){
return this.pIdFk;}
@Column(name="C_NAME")
public String getCName(){
return this.cName;}
//... setters, @Override hashCode(),equals()
}
@Entity
@Table(name="CHILD")
public class Child {
@EmbeddedId
@AttributeOverrides({
@AttributeOverride (name="pIdFk", column=@Column(name="P_ID_FK")),
@AttributeOverride (name="cName", column=@Column(name="C_NAME"))})
private ChildId childId;
@ManyToOne
@JoinColumn (name="P_ID_FK", referencedColumnName="P_ID_PK")
private Parent parent;
//... Constructors, getters and setters
}
test:
{
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Parent p = new Parent();
List<Child> cs = new Arraylist<Child>();
ChildId cId = new ChildId();
cId.setCName("xxx");
Child C = new Child();
c.setChildId(cId);
c.setParent(p);
cs.add(c);
p.setChildren(cs);
session.save(p);
System.out.println("pIdPk= "+p.getPIdPk());
System.out.println("pIdFk= "+p.getChidren().get(0).getPIdFk);
....
}
Output:
pIdPk= Auto_incremented values (works well)
pIdFk= 0 (Problem: how to have the same value as pIdPk?)
答案 0 :(得分:0)
经过多次尝试,似乎无法自动填充作为复合键一部分的外键。我找到了两种解决方法:1)首先坚持父母,然后读取pk值,设置fk值并坚持孩子; 2)使用ElementCollection。