Session#replicate() copies a detached entity into persistent storage while preserving its existing identifier. It is available only through Hibernate’s Session API and is useful when transferring data between logically separate databases, such as during migration or reconciliation. The source and target persistence contexts commonly use different EntityManagerFactory configurations, and the entity must be mapped in both. section 10.2.7
Select a ReplicationMode to determine how an existing target row is handled:
- IGNORE skips the entity when the target already contains the same identifier. section 10.2.7
- OVERWRITE replaces the target row regardless of its existing state. section 10.2.7
- EXCEPTION fails when the target already contains the same identifier. section 10.2.7
- LATEST_VERSION replaces the target only when the supplied entity has a newer version; it requires optimistic concurrency control with entity versioning. section 10.2.7
Copying an item between databases
Load an Item in one transaction, close its persistence context so it becomes detached, then replicate it through a Session connected to the target database: emB.unwrap(Session.class).replicate(item, ReplicationMode.LATEST_VERSION). Commit the target transaction and retrieve the item there. Hibernate checks the target according to the selected mode before flushing the resulting insert or update. section 10.2.7
Replication can cascade through associations with Hibernate’s REPLICATE cascade option. Hibernate checks associated identifiers, then writes existing rows as updates or missing rows as inserts when the persistence context flushes. This makes replication applicable to an entity graph, not only a single instance. section 13.1.4
The operation can also restore an audited entity to an earlier state: load an older Envers revision and replicate it with OVERWRITE. The restoration is recorded as a new audit-log update. section 13.3.4
