views:

319

answers:

3
+1  Q: 

Hibernate and IDs

Is it possible in hibernate to have an entity where some IDs are assigned and some are generated?

For instance:

Some objects have an ID between 1-10000 that are generated outside of the database; while some entities come in with no ID and need an ID generated by the database.

+1  A: 

I would avoid this and simply have an auxiliary column for the information about the source of the object and a column for the external identifier (assuming the external identifier was an important value you wanted to keep track of).

It's generally a bad idea to use columns for mixed purposes - in this case to infer from the nature of a surrogate key the source of an object.

Cade Roux
+1  A: 

You could use 'assigned' as the Id generation strategy, but you would have to give the entity its id before you saved it to the database. Alternately you could build your own implementation of org.hibernate.id.IdentifierGenerator to provide the Id in the manner you've suggested.

I have to agree w/ Cade Roux though, and doing so seems like it be much more difficult than using built in increment, uuid, or other form of id generation.

zmf
+1  A: 

Use any generator you like, make sure it can start at an offset (when you use a sequence, you can initialize it accordingly).

For all other entities, call setId() before you insert them. Hibernate will only generate an id if the id property is 0. Note that you should first insert objects with ids into the db and then work with them. There is a lot of code in Hibernate which expects the object to be in the DB when id != 0.

Another solution is to use negative ids for entities which come with an id. This will also make sure that there are no collisions when you insert an new object.

Aaron Digulla