Hibernate mapping association OneToMany with constraint restriction
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 persi开发者_StackOverflow社区sts A even though it has no B objects inside.
Do you know any solution for this?
Thanks in advance
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:
boolean onPreInsert(PreInsertEvent event)
Return true if the operation should be vetoed
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.
精彩评论