I'm trying to specify an identity field that is usually set by the database (as "native" identity properties are), but that can also be set explicitly by the application code (as "assign" properties are). (This behavior is needed for integration with legacy applications, test code, and code that can't use Hibernate.)
Using Hibernate 3.1, my approach has been to derive a class, CustomGenerator, from IdentityGenerator and override its generate() method. If the id is set then its serialized form is returned. Otherwise the POST_INSERTION_INDICATOR is returned to use the database-generated identifier. The problem I've encountered is that the database schema is generated with the auto_increment (MySQL dialect of 'native') only if the generator is the IdentityGenerator. To change this, I hacked SimpleValue.isIdentityColumn() to return 'true' if the generator class is IdentityGenerator or a derived class. As far as I can tell, everything now works properly with unset id's automatically generated and explicitly set id's inserted in the database correctly.
Did I re-invented the wheel here? Is there a better way to do this?
|