From How and when should I load the model from database for h:dataTable I love the idea of essentially caching data from a database in a PostConstruct method and subsequently accessing it in memory as many times as JSF wants to without a trip to the database, but I'm struggling with how to load and store it in memory. The classic object-to-relational impedance mismatch.
My model classes (beans, pure data objects) depend on other classes, i.e. objects contain other objects which are shared (e.g. a course has a student that is also in other courses). I am forced to do one of the following, all of which seem awkward:
- denormalize the in-memory data (beans) completely (different copies of the same student object appear in different course objects). I don't like copies of data which can get out of sync.
- use ID attributes (the course class has a studentID member). This necessitates looking up the student in the list of students using the ID whenever any student attribute is needed. Ecch.
- load all the data from bottom up in the contains hierarchy (load all the students, then load the courses, and for each course find the already-loaded related student object and put a reference to that object in the course object). This is a lot of searching but only has to be done once. If there are any circular references it won't work.
In addition, in order to make sure the model (the in memory data) is always in sync with the database, I would think that one would save and then load all the data every time the user changes any data, rather than incrementally change it in memory and then in the database and hope that I didn't forget to do this every time.
In a non-JSF application, it would not be heavy to hit the database with each user interaction unless the data were enormous, which would necessitate designing around performance rather than object-oriented anyway.
I am curious how others have approached this problem.