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 a Long 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 write Person p = new Person(...) but p.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 as savePerson(Person)), and they will do a check for the id being NULL or not to determine whether we should attempt to INSERT a new entity record, or UPDATE 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 the id 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:

  1. 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.)
  2. 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.
许可以下: CC-BY-SA归因
scroll top