最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

detached entity passed to persist on multi data source spring boot aspect - Stack Overflow

programmeradmin3浏览0评论

I am trying to replicate the data into 2 data sources on existing spring boot app for some migration work. I have spring aspect where after first transaction manager completes the transaction, I am trying to persist entity onto 2nd entity manager for replication and getting ".hibernate.PersistentObjectException: detached entity passed to persist:" error. What I am doing wrong? Is there better solution to do this?

@Aspect
@Component
public class ReplicatorAspect {
  @Autowired
  @PersistenceContext(unitName = "replication")
  @Qualifier("secondaryEntityManagerFactory")
  private EntityManager replicationManager;

  @Transactional("secondTxManager")
  @Around("execution(* com.demo.repository.*.save*(..)) && args(entity)")
  public Object logEntitySave(ProceedingJoinPoint joinPoint, Object entity) throws Throwable {
    boolean isCreateOperation = false;
    if (null == ((MyBaseEntity) entity).getId()) {
      isCreateOperation = true;
    }

    Object result = joinPoint.proceed();

    replicationManager.joinTransaction();
    if (isCreateOperation) {
      replicationManager.persist(result);
    } else {
      Object mergeObj = replicationManager.merge(result);
    }
    replicationManager.flush();
  }
}

I am getting below exception

Caused by: .hibernate.PersistentObjectException: detached entity passed to persist: com.demo.domain.TestEntity
    at .hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:120)
    at .hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55)
    at .hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
    at .hibernate.internal.SessionImpl.firePersist(SessionImpl.java:756)
    ... 169 common frames omitted

PS: My primary and secondary data sources are using same entity/dto and jpa repositories

发布评论

评论列表(0)

  1. 暂无评论