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.