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()
andequals(..)
contracts based on business keys. For example, for aUser
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 persisteduse
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
2010-10-03 07:18:39
Thanks, I think I'll go with the second option, will generate ids myself.
Abhijeet Kashnia
2010-10-03 08:08:16
@Bozho +1 for GUID article
Arthur Ronald F D Garcia
2010-10-03 15:09:07