I thought of a few solutions:
1. Dynamically change the generator class while restoring the database (I've seen people ask about this, but little in the way of replies)
2. Use native SQL to create stub records, but this involves that the application have knowledge of the db schema: very ugly.
3. In addition to the normal mapping for the entity class, have a dummy mapping using entity-name to distinguish it from the main mapping. This dummy mapping will use assigned ID generation, but will omit all properties other than the ID to reduce code duplication.
Option 3 looks to be the most promising. The mapping file looks like this:
Code:
<!-- proper mapping -->
<class name="com.acme.project.SubjectNode" table="subject_nodes">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="name" column="name" />
<!-- etc ... -->
</class>
<!-- dummy mapping, with just id and (implied) assigned ID generator -->
<class name="com.acme.project.SubjectNode" table="subject_nodes" entity-name="DummySubjectNode">
<id name="id" column="id" />
</class>
To restore an entity with a particular ID I do
Code:
Long nodeId = new Long(nodeEl.valueOf("@id"));
// First save dummy version of SubjectNode which has "assigned" ID generator
SubjectNode node = new SubjectNode();
node.setId(nodeId);
hsession.save("DummySubjectNode", node);
// Make sure dummy entity is actually in the database
hsession.flush();
// Now reload this entity using the normal mapping and populate the properties
node = (SubjectNode)hsession.load(SubjectNode.class, nodeId);
node.setName(nodeEl.valueOf("@name"));
// set other properties etc...
hsession.save(node);