Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should one include ID as a property on objects persisted to a database?

Tags:

orm

I am creating the model for a web application. The tables have ID fields as primary keys. My question is whether one should define ID as a property of the class?

I am divided on the issue because it is not clear to me whether I should treat the object as a representation of the table structure or whether I should regard the table as a means to persist the object.

If I take the former route then ID becomes a property because it is part of the structure of the database table, however if I take the latter approach then ID could be viewed as a peice of metadata belonging to the database which is not strictly a part of the objects model.

And then we arrive at the middle ground. While the ID is not really a part of the object I'm trying to model, I do realise that the the objects are retrieved from and persisted to the database, and that the ID of an object in the database is critical to many operations of the system so it might be advantageous to include it to ease interactions where an ID is used.

I'm a solo developer, so I'd really like some other, probably more experienced perspectives on the issue

like image 928
Crippledsmurf Avatar asked Jun 20 '09 13:06

Crippledsmurf


1 Answers

Basically: yes. All the persistence frameworks ive used (including Hibernate, Ibatis) do require the ID to be on the Object.

I understand your point about metadata, but an Object from a database should really derive its identity in the same way the database does - usually an int primary key. Then Object-level equality should be derived from that.

Sometimes you have primary keys that are composite, e.g first name and last name (don't ever do this!), in which cases the primary key doesn't become 'metadata' because it is part of the Object's identity.

I generally reserve the ID column of an object for the database. My opinion is that to use it for any 'customer-facing' purpose, (for example, use the primary key ID as a customer number) you will always shoot yourself in the foot later.

like image 191
gub Avatar answered Jan 04 '23 01:01

gub