Hibernate 7 — How to replicate entities with pre-assigned PKs to a second database?

Setup

Dual-database architecture: every write goes to a primary DB first, then needs to be
replicated to a secondary DB with the same primary keys, within the same transaction.

T result = primaryRepo.saveAndFlush(entity);  // assigns PK = x
secondaryRepo.save(result);                   // needs to INSERT with PK = x

We use a custom IdentifierGenerator that returns the entity’s existing PK if non-null,
so Hibernate can INSERT with a pre-assigned ID:

public Object generate(SharedSessionContractImplementor session, Object entity) {
    Long existingId = ((GObject) entity).getObjectId();
    if (existingId != null) return existingId;  // reuse primary-assigned PK
    return nextSequenceValue(session);
}

Environment: Hibernate 7.2.7.Final / Spring Boot 4.0.4 / JPA 3.2


Problem

result has PK = x but is detached from the secondary session. Both approaches now fail:

  • em.persist(detached_with_id)DefaultPersistEventListener.entityIsDetached()
    → fires merge internally → DefaultMergeEventListener.entityIsDetached()
    StaleObjectStateException

  • em.merge(detached_not_in_secondary_db) → same path, same exception

The entity also has @OneToMany(cascade = ALL) children that carry primary-assigned PKs,
so any of them can trigger the exception.

What is the cleanest / recommended way to replicate a full entity graph (including
cascade associations) with pre-assigned PKs to a second database in Hibernate 7?

The cleanest approach is to use your database replication features. Alternatively, you can try to make this work with a Hibernate event listener, which receives all the state. From there, you can trigger your insert/update/delete statements to the database directly.