February 19, 2004
DAO coding

I've spend some time recently putting together the DAOs for my project. Quite some time, in fact. God, they are ugly.

The Transfer Objects, the ones that ones that you end up using outside the persistence layer, seem usually to be coded as beans. So, the class which builds these objects has to set a bunch of properties:

principal.setPrincipalName(result.getString("PrincipalName"));
principal.setAddress1(result.getString("PrincipalAddress1"));
principal.setAddress2(result.getString("PrincipalAddress2"));
principal.setAddress3(result.getString("PrincipalAddress3"));
principal.setAddress4(result.getString("PrincipalAddress4"));
principal.setAddress5(result.getString("PrincipalAddress5"));
principal.setPostCode(result.getString("PostCode"));
principal.setContactName(result.getString("ContactName"));
principal.setContactPosition(result.getString("ContactPosition"));
principal.setTelephoneNo(result.getString("TelephoneNo"));
principal.setFax(result.getString("Fax"));
principal.setEmail(result.getString("Email"));
principal.setPredominantCurrency( result.getString("PredominantCurrency"));

There are similar (but not identical) bits of code all through this class; binding parameters into various bits of SQL, that sort of thing:

final String sql =
    "select "
        + StringUtils.join(MSSqlPrincipalDAO.FIELDS, ", ")
        + " "
        + "from "
        + MSSqlPrincipalDAO.TABLE
        + " "
        + "where "
        + StringUtils.join(MSSqlPrincipalDAO.KEYS, " = ? " + "and ")
        + " = ? ";
final PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, principal.getPrincipalNumber());
statement.setString(2, principal.getPrincipalSequence());

To my Python-educated eye, this looks hideous. The field names are repeated all over the place, and putting them into constants isn't any better. The bean-property to SQL column mapping is also repeated several times - very error prone. But in Java, I can't think of a cleaner, less repetitive way of doing it. Am I missing something super-elegant?

Building the Transfer Objects as Maps would be a lot prettier, I know. But then using them would be a bit painful, so I don't want to do that. :-(

Another question; I went through this code replacing all the SQL construction literals (like "select ", for example) with constants. But it seemed to me that this made the code less readable, and no more maintainable. So I'm leaving the literals in. Will the code-police be able to make a good case against me?

BTW, clearly these DAOs could be generated automatically. Are there any good tools for this? (Other than sql2java, which I've tried; I can't get it to work.) If not, I think I feel some Python coming on...

Posted to Java by Simon Brunning at February 19, 2004 02:06 PM
Comments
Post a comment
Name:


Email Address:


URL:



Comments:


Remember info?