I have a Many-to-Many relationship between a persistent object (retrieved by a query) and a newly created transient object (created with new, not yet persisted). They are connected via a @JoinTable association, such as:
@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(name = "adccol开发者_运维问答lectiontype_cn_node_type", joinColumns = {
@JoinColumn(name = "idadccollectiontype")
}, inverseJoinColumns = {
@JoinColumn(name = "idcn_node_type")
})
and on the other end:
@ManyToMany(mappedBy="cnNodeTypes", cascade=CascadeType.ALL)
Note CascadeType.ALL
.
If I simply create an association between these two objects by adding each to the other's collection, and persisting later (another object, and rely on cascading) then the join table is not updated.
However, if I manually persist
the transient object before doing the association it seems to work.
Now I've tried to find some info about this case, why and how it works, but I couldn't find any explanation. Maybe someone can enlighten me, whether what I assume is right or not, and the reason behind it.
I'm not sure there is enough information to really explain it. If you are modifying a managed entity, the changes should be picked up when the transaction commits or flush is called. So, is the existing entity managed in the current EntityManager context? Does the following work?
ManagedEntity oe = em.find(ManagedEntity.class, id);
NodeType nt = new NodeType(id);
oe.getCnNodeTypes().add(nt);
nt.getOtherEntityCollection().add(oe);
em.flush();
You could also try calling merge on your managed entity to have it cascade to the new entity instance.
精彩评论