views:

31

answers:

1

I have an entity in my system, which naturally needs an identifier so that it can be uniquely identified. Assuming the database is used for generating the identifier with Hibernate, using the native strategy, then obviously the application code is free of this resposibility of assigning identifiers. Now, can an instance of that entity be considered valid before it is persisted and gets its identifier? Or should I use some other strategy to assign my entities their identifiers so that it gets its identifier when its constructor is called?

+2  A: 

That's an extensive topic, but here are two possibilities:

  • define your hashCode() and equals(..) contracts based on business keys. For example, for a User entity, this would be the username, rather than the auto-generated id. Thus you will be able to use the entity in collections before it is persisted

  • use UUID as a primary key, and handle the generation yourself. See this article by Jeff Atwood and this article demonstrating a way to use it with Hibernate

(Since you mention DDD and hibernate, take a look at this article of mine)

Bozho
Thanks, I think I'll go with the second option, will generate ids myself.
Abhijeet Kashnia
@Bozho +1 for GUID article
Arthur Ronald F D Garcia