Creating/updating entity save strategy
https://softwareengineering.stackexchange.com/questions/264899
-
06-10-2020 - |
Вопрос
Please note: although I'm talking about Java in this question, what I'm asking about here should really be language-agnostic.
I am dabbling in OR/M for the first time, and have cooked up the following "update strategy" for all of my entities:
- All entity POJOs extend an abstract base class
BaseEntity
that has aLong id
property, for that entity's unique id/primary key - Applications are free to create instances of an entity, but all constructors/factory methods omit the setting of this
id
property - Hence if
Person extends BaseEntity
, then I can writePerson p = new Person(...)
butp.getId()
is NULL. - Only when you call the entity's DAO method does the entity get saved to persistence and is given an
id
. - My DAOs will only have a
save*
creational method (such assavePerson(Person)
), and they will do a check for theid
being NULL or not to determine whether we should attempt toINSERT
a new entity record, orUPDATE
an existing entity record. - My DAO
save*
methods will always return an instance of the entity that was just created/updated, but will make sure that theid
is now properly set (if it wasn't before).
To me this is logical/sensible, but seems a bit complicated/convoluted. Am I going about this the wrong way, are there better "update patterns" for OR/M that take care of this for me? I plan on doing everything in raw JDBC at first, and then eventually migrating to Hibernate once I'm more comfortable.
Решение
It sounds/looks good, I would just offer these suggestions:
- Might want to include a timestamp in the
BaseEntity
to resolve conflicts. For example, what if two people are editing the record at the same time. You can then develop conflict resolution strategy based on this value (last one in wins, etc.) - Ideally every table should have a natural key to check for uniqueness. But the surrogate key works well. Just bear in mind if it's a surrogate key it should always come from your application not the client or caller. Don't expect the information from the client or caller to always be accurate. This is where natural keys help out.
Не связан с softwareengineering.stackexchange