Ask HN: Java & SQL advice
The issue is 'select' calls to the (SQL) database.
These are all implemented as endless chunks of copy and paste data that do nothing but move fields from queries into class members. It's butt ugly and I want to get rid of it.
A nice sample:
Map<Integer,Questionnaire> questionnaires = new HashMap<Integer,Questionnaire>();
Connection connection = null;
PreparedStatement statement = null;
ResultSet rs = null;
try {
connection = DBStore.getReadConnection();
String SQL = "SELECT questionnaire_id,order_id,label FROM questionnaires ORDER BY order_id";
statement = connection.prepareStatement(SQL);
rs = statement.executeQuery();
while (rs.next()){
Questionnaire questionnaire = new Questionnaire(rs.getInt(1), rs.getInt(2), rs.getString(3));
questionnaires.put(questionnaire.getQuestionnaireId(), questionnaire);
}
} catch (SQLException e) {
logger.error(e.toString(), e);
} finally {
DBStore.closeAll(connection, statement, rs);
}
return questionnaires;
(yes, I know, it's pretty ugly).So, I came up with a solution, which essentially does the mapping of database fields to class members based on the field names as returned by the database during the query.
You pass it a class and it figures out the rest.
That works.
But it has another problem. Because the classes that are being stored in the SQL database and the class that takes care of the storing and retrieving of the data are not in the same package or derived from each other I'd have to make all the fields that I wish to store in all the classes 'public'.
Is there an elegant way around this ?
How do others do this kind of stuff ?
I can't believe that this is the way it is really done, so if any of you has any clue or pointer then please help me out before I throw my monitor out of the window...