Re: How to implement simple DB persistence
On Sun, 15 Aug 2010, tnorgd wrote:
I have a bunch of classes (say, 5-10) that I would like to serialize
into an SQL database. I decided to implement this on my own, because:
- I need to keep control over the data; not all the fields from a
class need to go into DB
- the DB storage format must be easy for humans who are browsing the
DB; there are also scripts in R for data analysis that will read from
- Stuff like Hibernate is a too heavy gun for it;
How heavy do you think that gun is, and how light would a gun have to be
to be acceptable to you?
My original idea was to add a constructor initialized with SQL
connection, or a pair of static methods for reading from / writing to
a DB into each of my classes.
The latter, but don't make them statics in the domain model class, make
them instance methods on some sort of Persister object. Keep the
persistence logic as far from the domain model as you can.
Can you share some advices or some parts of working code for some
I got nothin'.
If you want to use foreign keys in the database, you may need to
topologically sort object graphs before persisting them. There are
well-known algorithms for this, but implementing them might be a pain.
PS. Another issue with it is that my data comes from experiments and
each observation (rather than an object) is unique. What I mean is that
(as I understand) in typical persistence approach each Java object can
be serialized / deserialized as a unique entity. In my case each row of
data is unique and DB must store exactly one copy of it, no matter how
many objects keep this data. Luckily I have a way to annotate the rows
(e.g time stamp or measurementID)
Object-relational mappers, like Hibernate and other JPA providers, also
have this concept of entity identity that's stronger (in a sense) than
simple object identity. This constraint would follow naturally from a JPA
The players listen very carefully and respectfully to all that the clever
men have to say about what is to happen in the next generation. They
players then wait until all the clever men are dead, and bury them
nicely. Then they go and do something else. -- The Napoleon of Notting
Hill, G. K. Chesterton