We have a large immutable object graph constituted of many immutable entities (values from the model perspective) that are all uniquely identified by an id and a version.
E.g.
Code:
class DocumentSnapshot {
final int id;
final int version;
final Set<ItemSnapshot> items;
//...
}
class ItemSnapshot {
final int id;
final int version;
//...
}
What we would like is to only have a single copy of every snapshots in the DB.
DocumentSnapshot ds = new DocumentSnapshot(1, 1, [ new ItemSnapshot(1, 1) ]);
save(ds); //should store both as the snapshots never been stored
ds = new DocumentSnapshot(1, 1, [ new ItemSnapshot(1, 1), new ItemSnapshot(2, 1) ]);
save(ds); //should only store new ItemSnapshot(2, 1) since the other entities would already exist in the DB.
If I was solving this issue with plain SQL I'd loop over the values in the graph, try to INSERT, catch UNIQUE CONSTRAINT violations and ignore them (all in one transaction), but I'm a bit puzzled on how this could be achieved in Hibernate. Please note that the only features we can use are XML mappings and general persistence hooks (we are actually programming in ColdFusion, which uses Hibernate for it's persistence mechanism under the hood).
One idea I'd have if I could implement the `Persistable` interface (in java) would have been to force Hibernate to always insert by overriding the `isNew` function and then perhaps somehow solve conflicts with DB triggers, but I can't.
Any ideas?