Hibernate 映射关联 OneToMany 与约束限制
我有以下代码:
@Entity
class A{
@Id
private Long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "a", cascade = CascadeType.ALL)
private List<B> bs =new ArrayList<B>();
...
}
@Entity
class B{
...
@ManyToOne(fetch = FetchType.LAZY, optional = false, cascade = CascadeType.ALL)
@JoinColumn(name = "aId", nullable = false)
private A a;
}
我希望 hibernate 不保留 A if bs.isEmpty()。
使用此代码,hibernate 会保留 A,即使它内部没有 B 对象。
你知道有什么解决办法吗?
提前致谢
I have the following code:
@Entity
class A{
@Id
private Long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "a", cascade = CascadeType.ALL)
private List<B> bs =new ArrayList<B>();
...
}
@Entity
class B{
...
@ManyToOne(fetch = FetchType.LAZY, optional = false, cascade = CascadeType.ALL)
@JoinColumn(name = "aId", nullable = false)
private A a;
}
I want hibernate NOT to persist A if bs.isEmpty().
with this code, hibernate persists A even though it has no B objects inside.
Do you know any solution for this?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您不能使用注释添加约束。
我认为你所要求的可以通过实现一个事件监听器来完成,它接收所有正在完成的插入。请参阅 Hibernate 手册,第 12.2 章 - 事件系统 和 PreInsertEventListener 的 javadoc。具体来说,我相信这个方法可能对您有用:
从传递的事件中,您可以获得将通过 PreInsertEvent。
在 onPreInsert 方法中返回 true,您将停止插入。
请记住将侦听器安装在
hibernate.cfg.xml
文件中。I don't think you can add a constraint using annotations.
I think what you ask can be done implementing an Event Listener, which receives all the inserts which are being done. See the Hibernate manual, chapter 12.2 - The Event System, and the javadoc for PreInsertEventListener. Specifically, I believe that this method may be useful to you:
From the event passed, you get the instance of the object that will be inserted through the method
getEntity()
of the PreInsertEvent.Return true in the onPreInsert method and you'll stop the insert.
Remember to install the listener in the
hibernate.cfg.xml
file.