Hi,
I using hibernate for the persistence of a wide set of Java objects. I am currently persisting as entities, and mostly things are fine.
However, there are a couple of areas where I require to improve the logic in the persistence process, and am not sure whether I can achieve this with the mapping, or whether it needs application level logic. Let me explain with an example.
To handle storing exceptions into the database, there are 2 tables
Exception
-----------
id long
category long
description varchar
ExceptionCategory
---------------------
id long
categoryName varchar
There are corresponding Java classes for Exception and ExceptionCategory, with the Exception having a property of type ExceptionCategory. I am mapping this as a uni-directional many-to-one from Exception to ExceptionCategory, with category being a foreign key to the ExceptionCategory's id column.
Scenario 1
------------
The application instantiates an ExceptionCategory object, setting the categoryName to "cat1". Also, an Exception object is instantiated, and the category propery is set to the ExceptionCategory object. After saving, there is a new row in each of the tables, and they are related by the id/category FK. All is well so far
Scenario 2
------------
The application wishes to create another exception of category "cat1", so it instantiates both an ExceptionCategory and an Exception as above, and persists. Now there are 2 rows in each table. The ExceptionCategory has 2 entries for the same value of categoryName.
I appreciate that these 2 objects have seperate "identity", and that is why there are 2 seperate rows.
The behaviour I would like to see is that if an entity already exists that has a defined value in a property (e.g. categoryName) then use the existing entity for the relationship.
I know I could do a HQL query from the ExceptionCategory table to get the entity that relates to a given category, but I was wondering if there is a way to express this in the mapping file?
Any pointers would be appreciated.
Brian.
|