Wednesday, December 05, 2007

How Important is Symmetry in JPA?

When you are designing a domain model using JPA or hibernate or another declarative approach to ORM, you must decide the cascade rules for creating and deletign objects that are related to each other. When you have a one-to-many relationship between two objects, when an object is persisted, you need to decide if the related object should be automatically persisted as well, or should you have to persist each object?
To me it seems that this must be made symmetrical, that is if you cascade create, then you should cascade delete as well. Any other rule than this makes your system more complicated. Intuition should be available to one trying to understand your domain model, and symmetry is a part of nature, so it will be intuitive to expect a consistent behavior. If you are using JPA, the cascade rules will be in the code so you will see the rule with the code so it will be evident of your choice. In the case that you are using Hibernate from an XML configuration file that is not visible at the same time as the source code, then you will have to remember the cascade rules, minimizing the burden of memorizing too many things can help in comprehending your model, a consistent rule of always cascade create with delete will eliminate this from your efforts.
In a more encapsulated direct approach, I recommend that a new annotation of @Aggregation be created that has this behavior as it's meaning, it is simple and precise as to the intent. AspectJ can be used to create this annotation, and with JPA annotations as the ORM approach, the needed annotations can be injected behind the scenes. This seems like a nice clean use of AOP to help in using of JPA.

3 comments:

Doug said...

I wonder if the rules are dependent on the purpose. For example, you wouldn't want to delete sales order history just because you prune your customer profiles, as the history is useful for year of year analysis, etc.

mike said...

I would suggest that the behavior you desire would depend on your requirements, so maybe what data you perform analysis on would be collected with the observer design pattern type of collector, like a trigger, but in oo terminology, if you used the data for a specific purpose, you would define the model for the particular purpose, and evolve the old data into the updated schema.

Doug said...

I'm just leery of cascading deletes particularly in the enterprise environment where the schema evolution may be somewhat nebulous at times, where-as I can see the value of cascading creates

Labels