0

I am using EclipseLink 2.3.3. with a data model with about 100 entities. I have a Java class mapped to each database table using annotations.

I have two use cases to implement. One is that a new record enters the system that hits about 60-75 of the tables. For this case, I want merge and persist to cascade, so that I can just merge the top level object and have that cascade to all related entities.

Another use case is that I need to insert a collection of individual objects, often one from each of a bunch of different tables. In this case I don't want the cascading merge, because I need to have control over the insertions. If I have cascade enabled, merging the first object might or might not merge the other objects, depending on if or how they are related, so I'd rather explicitly merge each of them.

So essentially, I want cascading merge and persist in one situation, but not another. So if I include the cascade annotations in the mapped classes, I need to selectively disable the cascading for certain operations; or, if I turn off cascading in the mapped classes, I would like to enable cascading for certain operations.

So far I am not finding any way to selectively turn on or off cascading for a particular operation. There is a CascadePolicy class but that seems to only be used with queries. There are dynamic entities, and I was thinking perhaps I could use that to do something like create a dynamic entity from an existing entity and turn off the cascading behavior on that entity's relationships and somehow use that for the merge, but I have not been able to find the right API for that.

So I am wondering if there is a better answer somewhere that I'm overlooking? Thanks for any information.

4

1 回答 1

1

我不确定您所追求的控制级别,尤其是在您提到要插入单个对象的情况下。从它的声音来看,级联合并正是您想要的实体对象树在第一种情况下与 EntityManager.merge 一起使用。对实体调用的合并将检查它是否是新的,并酌情更新或插入。将关系标记为级联合并将允许查找新对象并插入它们。

第二种情况虽然您想处理单个插入,但为什么不排除映射上的级联持久选项,而只在要插入的对象上调用 EntityManager.persist 呢?然后 Persist 不会级联,因此只有您调用 em.persist 的实体会被插入。关系将仅用于设置外键值 - 尽管您可能希望将它们保留为空并稍后将它们设置为更大的合并调用的一部分。双向关系的双方都需要维护,如果对方存在且没有被合并,则不存储其关系变化。

如果这不是您想要的,EclipseLink 在 UnitOfWork 上有本机 API(EntityManager 本质上包装了 UnitOfWork 用于事务工作),允许您指定合并策略。参见 UnitOfWork 上的 mergeClone、deepMergeClone 和 shallowMergeClone,它们本质上分别使用 CASCADE_ALL_PARTS、CASCADE_PRIVATE_PARTS 和 NO_CASCADE 作为合并策略,而 JPA 合并使用 CASCADE_BY_MAPPING。

于 2012-11-14T21:54:38.367 回答