Database Programming the Hard Way
I imagine a lot of people have this problem – There’s a little persistent data for an application, it would be easiest to be in a database, but the frameworks are overkill. The solution, or so I’ve heard, is to use POJOs – Plain Old Java Objects. But, if I understand this correctly, I’m still left to hand-code the translation from field variables to database variables, usually in a rather tenuous way (i.e. changes to the database required multiple changes to the object – the field name, the getter/setter name, and the string of SQL that inserts/updates it).
My Java objects that actually hold data tend to end up looking like this:
public class ConfigData {
private String configName;
private Date configDate;
private int configKey;
//getters
//...
//setters
//....
/** Insert items into database */
public void insertSelfInto(Connection conn) {
Statement stmt = conn.createStatement();
int rows = stmt.executeUpdate("INSERT INTO "+
"ConfigData (configkey, configname, "+
"configdate) VALUES ("+configKey+
", '"+configname+"', "+configdate+")");
if (rows == 0) {
//throw an exception
}
}
This is really ugly. I mean nasty ugly. I mess up the single quotes around strings all the time, I’m crafting SQL by hand based on variable names and column names that are hard coded, etc. It’s not obtuse, and it is straightforward, but it is definitely finicky.
So I’ve been trying to determine if this is really how POJOs are supposed to work, or am I missing some intermediate step? This is sort of the lowest level POJO you could use, but is there something short of a framework, or adding another JAR to my project that would give me some more stability, or at least readability? I have yet to discover it, if there is.