@OneToOne和@JoinColumn,自动删除空实体,可行吗?
我有两个实体,具有以下JPA注释:
@Entity
@Table(name = "Owner")
public class Owner implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;
@OneToOne(fetch=FetchType.EAGER , cascade=CascadeType.ALL)
@JoinColumn(name="Data_id")
private Data Data;
}
@Entity
@Table(name = "Data")
public class Data implements Serializable
{
@Id
private long id;
}
所有者和数据具有一对一的映射,拥有方是所有者。 当我执行时出现问题: owner.setData(null) ; ownerDao.update(owner) ; “Owner”表的 Data_id 变为 null ,这是正确的。
但“数据”行不会自动删除。 我必须编写另一个 DataDao 和另一个服务层来包装两个操作( OwnerDao.update(owner) ; dataDao.delete(data); )
是否可以在拥有的 Owner 将其设置为 null 时自动删除数据行?
I have two Entities , with the following JPA annotations :
@Entity
@Table(name = "Owner")
public class Owner implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;
@OneToOne(fetch=FetchType.EAGER , cascade=CascadeType.ALL)
@JoinColumn(name="Data_id")
private Data Data;
}
@Entity
@Table(name = "Data")
public class Data implements Serializable
{
@Id
private long id;
}
Owner and Data has one-to-one mapping , the owning side is Owner.
The problem occurs when I execute : owner.setData(null) ; ownerDao.update(owner) ;
The "Owner" table's Data_id becomes null , that's correct.
But the "Data" row is not deleted automatically.
I have to write another DataDao , and another service layer to wrap the two actions ( ownerDao.update(owner) ; dataDao.delete(data); )
Is it possible to make a data row automatically deleted when the owning Owner set it to null ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据您的休眠版本,使用:
在@OneToOne注释文档上使用cascadeType:DELETE_ORPHAN或orphanRemoval=true
:http://docs.jboss.org/hibernate/core/3.3/reference/en/html/objectstate.html#objectstate-transitive
我'我从未在 OneToOne 上尝试过,但从文档来看,它应该可以工作。
或
编辑:
我发现这个帖子:Hibernate 缺乏对一对一和多对一关系的删除孤儿支持的解决方法?
所以也许它不起作用。然而,这两个答案描述了两种不同的解决方法。
Depending on your hibernate version, use :
use the cascadeType : DELETE_ORPHAN or orphanRemoval=true on the @OneToOne annotation
documentation : http://docs.jboss.org/hibernate/core/3.3/reference/en/html/objectstate.html#objectstate-transitive
I've never tried it on OneToOne, but from the doc, it should work.
or
EDIT:
i found this SO post : Workarounds for Hibernate's lack of delete-orphan support for one-to-one and many-to-one relationships?
So perhap's it's not working. The two answers describe two different workarounds however.