You are here: db4o Databases Replication > Bidirectional Replication

Bidirectional Replication

It's quite often the case that you need replication in both directions. For example when you have a mobile device which keeps the data in sync with a desktop PC. Changes on the both partners have to be replicated to the other partner.

First, make sure that you've prepared and configured db4o properly. See "Simple Example"

Start a replication-session with the two replication partners. Note that no replication direction is set.

ObjectContainer desktopDatabase = openDatabase(DESKTOP_DATABASE_NAME);
ObjectContainer mobileDatabase = openDatabase(MOBILE_DATABASE_NAME);

Db4oEmbeddedReplicationProvider providerA = new Db4oEmbeddedReplicationProvider(desktopDatabase);
Db4oEmbeddedReplicationProvider providerB = new Db4oEmbeddedReplicationProvider(mobileDatabase);

ReplicationSession replicationSession = Replication.begin(providerA, providerB);
Db4oReplicationExamples.java: Prepare bidirectional replication

Then get the changed objects from both replication partners. Each replication partner returns the updated and created object in a object-set. Then iterate over both object-sets and replicate the changes.

// First get the changes of the two replication-partners
ObjectSet changesOnDesktop = replicationSession.providerA().objectsChangedSinceLastReplication();
ObjectSet changesOnMobile = replicationSession.providerB().objectsChangedSinceLastReplication();

// then iterate over both change-sets and replicate it
for (Object changedObjectOnDesktop : changesOnDesktop) {
    replicationSession.replicate(changedObjectOnDesktop);
}

for (Object changedObjectOnMobile : changesOnMobile) {
    replicationSession.replicate(changedObjectOnMobile);
}

replicationSession.commit();
Db4oReplicationExamples.java: Bidirectional replication