Hi,
I need an advice on how to cope with staticly created entities.
Code:
/**
* base entity with common properties
*/
public class DomainEntityBase {
private long id;
private String name;
public DomainEntityBase() {}
public DomainEntityBase(long id, String name) {
this.setId(id)
this.setName(name);
}
// etc.
}
Code:
/**
* some domain entity
*/
public class SomeDomainEntity extends DomainEntityBase {
public final static SomeDomainEntity FOO = new SomeDomainEntity(10, "Foo");
public SomeDomainEntity() {}
public SomeDomainEntity(long id, String name) {
super(id, name);
}
// etc.
}
All our mappings work with native id generation -- DomainEntityBase.id mapped to the surrogate primary key column, with Hibernate identifying
new objects by an id-unsed-value of 0.
Some of your business objects (like "FOO") are
known in advanced, so they are statically constructed, including id-assignment. There is no need to load them from storage (except when traversing the object graph) -- firstly because "they are known in advanced" and secondly because they are used in various places, where we can't possibly load them from storage via hibernate (frankly mostly because it's cumbersome).
Hibernate doesn't care, where or how objects are constructed. All it cares about is its persistent state. This is OK, as hibernate properly inserts those
transient objects. However, after application (re)start from hibernates point of view those statically constructed objects will again be in
transient state, whether they exist in the database or not. This leads to the inevitable problems of either (a) a primary-key-constraint-violation-exception, when hibernate tries to reinsert objects; or (b) Hibernate reassigning the speficied id, which is simply wrong.
How do I solve this problem without coupling my domain model classes to hibernate?
Note: We are using a DAO-based storage manager on top of Hibernate, which delegates to Hibernate.
Hibernate version: 3.2.6