Trouble synchronizing between Model & View using Hibernate & JSF
Joined: Oct 08, 2005
I have a webapp with JSF as the view technology, Hibernate 3 for persistence and Spring. What I have trouble conceptualizing is the coordination with persistent entities and their corresponding view entities when a bi-directional association exists between entities.
For example, I have the following entities:
1. A File object. 2. A Catalog object. 3. A User object.
A User has 0...N Catalog objects. Therefore in a User class, there is a List of Catalog objects. This is specified in the User.hbm.xml file using a <list> element. In the Catalog class, I have a reference to a User object; which is denoted in the Catalog.hbm.xml file with a <many-to-one> element. There is a foriegn key restraint on the Catalog table where the User_Id column refers to the User_Id column in the Users table.
A Catalog has 1...N File objects. The Catalog & File classes have similar <set> and <many-to-one> elements in their xml files as described above for User and Catalog objects.
Now I have tried two approaches to coordinating between what must be displayed in the View layer and the Model layer. One approach was to have my View classes extend their corresponding Model class, with the persistent properties being declared as protected in the Model class. However, I have a problem because a User object has a List of Catalog objects, while a UserView object needs to have a List of CatalogView objects. So there exist two different List objects in the UserView object, where, there should really be only one list. And I have trouble coordinating these two lists when I have to persist data that has changed in the View.
The other approach was to have seperate classes for the Model & View, and use a Builder strategy to generate one type of class from the other. But the problem here is that, for example, the association is bi-directional. So lets say a Catalog has changed state in the View, then I need to persist it. So a CatalogBuilder will take a CatalogView object and attempt to generate a Catalog object. However, the CatalogView has a reference to a UserView object, so a UserBuilder must be employed to generate a User object for the corresponding UserView object the CatalogView contains a reference to. But again, this UserView has a reference to a List of CatalogView objects, which then require a CatalogBuilder to generate corresponding Catalog objects for. You can see how this will go on forever then.