Is there a commonly-accepted practice for designing java objects that are frequently loaded and saved to and from databases?
The approach that I'm using now is to have one main database object which opens a connection to the database. Anywhere in my application where I need to load or save objects, I create a source interface for loading and saving. For example, I might do something like this:
public interface CalendarSource { public Appointment[] getAppointmentsForMonth(int year, int month); public void saveAppointment(Appointment appointment); }
Then I would implement that interface on the main database object. Any sub-data is also loaded at the same time into member objects inside the main objects. Like if there's a list of guests for each appointment. This works well, since all of the data I'm using comes from one of two databases, so I keep two database connections around, and each source is implemented by one of them.
The problem is that this just seems unwieldy at times. It's confusing how to handle ID values, since I really don't want to add them to my objects. It also requires one database connection to implement several different interfaces. Effectively, my database package has to rely on almost every package in the project because it implements all of the interfaces. This does make sense on a certain level, but I'm wondering if there's a better way.
There are two main reasons why I chose this architecture:
- I'd like the objects that I use to not know that they are loaded or saved from a database. I might want to replace this database source in the future with flat files for portability.
- I'd like to have a good package dependency hierarchy. The database code should be isolated so a change to the database schema can be easily updated to the code.
The one problem that I run into is what to do about ID values. Since the objects shouldn't know they are database objects, they shouldn't have an ID field in them. But, if I try to write an object to the database, and I don't have the ID value, how am I supposed to know if I should do an insert or an update?
I'm also concerned about having the database package extend everything throughout the whole project. I'm constantly passing these source interfaces around. I suppose that makes sense, too.
Maybe I'm just looking for some validation that I'm doing it right, and there's not some obvious simple solution here that I'm not seeing. Don't get me wrong - everything works just fine.
Any thoughts?