This feature is not something you want to use generally. When you want to persist your objects with a previously generated identifier, you can use replicate()
.
Example Usage For System Up-gradation
Suppose you need to upgrade your system with some new features and removing some old ones. Now you want to migrate your existing database to the new one, facilitating your new requirements. The session.replicate()
can be useful like below:
myNewObject.setId(myOldObject.getId());
myNewObject.setExistingProperty(myOldObject.getExistingProperty());
myNewObject.setNewProperty("my new property");
session.replicate(myNewObject, ReplicationMode.EXCEPTION);
Example Usage For Rolling Back Changes Made in non-ACID Transactions
Suppose your database became inconstant while doing some non-ACID transactions. Say, You have two classes in your system named, Course
and Student
. During a non-ACID transaction, say student1
object is persisted with course1
, where student1
object is already given an id for course1
, but course1
is not persisted due to some error. For that reason your DB becomes inconsistent (student1
is enrolled for a non-existent course). To repair your inconsistency, you simply create a new Course
object with the data and id
of course1
and persist it using session.replicate()
.