Im pretty much at the beginning of my first Java application that has a local database at its back end.
Following some examples posted for me using the JPA im now looking at design patterns etc but have a couple of questions up front.
1. When working with any kind of persistence (file, database), should the objects be responsible for the persistence e.g I have an Asset class, should this class have a method like addToDatabase() or is this better handled elsewhere. If so are there any principles that should be applied.
2. Im guessing the way to work with my objects and data is to create objects from the data rather than working with the data directly. E.g I have an Asset record in the database, I create a "new Asset(with its corresponding data) object", manipluate the object using its getters and setters and then write that data back to the database. Am I way off the mark?
I may be trying to run before I can walk but I have to start somewhere.
1). For me it worked best to separate the actual data and the database management. This way your data objects can be simple POJOs and you can easily reuse them in any place or even another application without having the database functionality included in the objects.
I found it useful to have a manager class for each data class or a common manager class for all your data objects and do all database interaction within these manager class(es). I've always made good experiences with this approach but perhaps someone other may have a better idea.
2.) This sounds like a reasonable concept. Use annotated POJO data objects for each entity you discovered for you application. Fill it with data or read data from it and only interact with the database via an entity manager only when it's really necessary. For good performance it's better to avoid unnecessary database round trips Of course you have to take care of correct transaction handling if you're using the same data objects from multiple threads for example. With the JPA a transaction usually lasts for the method you're in. After your method returns the entity bean gets unmanaged and the database don't know of any changes until you update it with the entity manager. So you have to take care to update your entity beans or your database when needed.