OneToMany 关系上的 Hibernate Cascade 操作给出更新查询
@Entity
@Table(name="table1")
public class Parent{
@Id
@Column(name="Parentid")
private String Parentid;
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
@JoinColumn(name="Parentid" referencedColumnName="Parentid")
private List<Child> objChild;
.....//getters and setters
}
子级使用复合主键。其代码是: -
@Embeddable
public class ChildPk{
@Column(name="...")
private String str1;
@Column(name="...")
private String str2;
.....//getters and setters
}
@Entity
@Table(name="table2")
public class Child{
@Column(name="Parentid", nullable="false")
private String Parentid; //this the foriegn key referencing Entity1
@EmbeddedId
private ChildPk objChildPk;
.....//getters and setters
}
根据上面的代码,我有一个父子一对多关系。子项包含一个复合键作为其主键。
我使用复合键填充子项,将其添加到父项,填充父项,然后使用 session.save() 保存父项。这样就成功地在 Child 上执行了插入语句。同样,如果我尝试插入另一个 Child 对象,但包含与之前相同的复合键但外键不同,然后尝试再次保存 Parent 对象,它实际上会使用新的 Parentid 更新 Child 中的现有行。
根据关系数据库,我的理解是子表中复合键的重复条目应该无法插入。但是,Hibernate 正在更新现有行,因为值相同(??)。我尝试为复合键插入不同的值,它在子表中插入得很好。
我希望我努力让你正确理解这个问题。两个表之间存在单向一对多关系,其中更新具有相同值的行。
我很困惑这是一对多还是复合键的问题。
@Entity
@Table(name="table1")
public class Parent{
@Id
@Column(name="Parentid")
private String Parentid;
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
@JoinColumn(name="Parentid" referencedColumnName="Parentid")
private List<Child> objChild;
.....//getters and setters
}
Child uses composite primary key. and the code for that is:-
@Embeddable
public class ChildPk{
@Column(name="...")
private String str1;
@Column(name="...")
private String str2;
.....//getters and setters
}
@Entity
@Table(name="table2")
public class Child{
@Column(name="Parentid", nullable="false")
private String Parentid; //this the foriegn key referencing Entity1
@EmbeddedId
private ChildPk objChildPk;
.....//getters and setters
}
As per the above code, i have a Parent to Child one-to-many relationship. And the Child contains a Composite key as its Primary Key.
I populate the Child with a composite key, add it to Parent, Populate Parent, and save Parent with session.save(). This execute insert statement on Child successfully. Same way, if i try to insert another Child object but containing same composite key as earlier but different foreign key and then try to save again the Parent object, it actually updates the existing row in Child with new Parentid.
As per relational database, my understanding was that duplicate entry of composite key in Child table should fail to insert. But, Hibernate is updating the existing row because values are same (??). I tried inserting different values for composite key and it inserts fine in Child table.
I hope i am trying to make you understand the problem correctly. There is a unidirectional one-to-many relation between two tables where updates are happening with rows that have same values.
I am confused is it a problem of one-to-many or of composite key.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论