Question

I am trying to build a simple, lightweight "DAO layer" for my app that just uses pure JDBC (nothing fancy like Hibernate, TopLink, MyBatis, etc.).

public class AnimalDAO extends BaseDAO<Animal> {
    private AnimalType type;
    private String name;

    public void insertAnimal(Animal animal) {
        StingBuilder sql = new StringBuilder();
        sql.append("INSERT INTO animals (");
        sql.append("animal_type_id, animal_name ) VALUES (");
        sql.append(animal.getType().getId());
        sql.append(animal.getName());
        sql.append(" )");

        doSQL(sql.toString());
    }
}

public class BaseDAO<T> {
    private Long id;

    protected T doSQL(String sql) {
        // Typical JDBC code to hit a database with the "sql" query and return a ResultSet.
        ResultSet result = queryDatabase(sql);

        // Now, how do I turn "result" into type T such that, in the case of 
        // AnimalDAO#insertAnimal(Animal), result gets converted into an Animal?
        return ???;
    }
}

So the idea is to have a doSQL(String) method in the BaseDAO that will take care of all the boilerplate JDBC stuff (making prepared statements, connection pooling, try-catch blocks for transactional commits, etc.). Then, subclasses like Animal just need to tell doSQL which query to execute.

The problem is, I'm not sure how to convert the JDBC ResultSet into the appropriate T generic type, which in the case of AnimalDAO is Animal. Any ideas? Thanks in advance!

Was it helpful?

Solution 2

It appears to me that what you need is for BaseDAO to be abstract with an abstract transform method. The method (protected abstract T transform(ResultSet) for example) can then be overridden by extending classes (AnimalDAO) such that the extending class knows how to transform its own type. Then the doSQL method will have a return line something like return transform(result);

OTHER TIPS

Yes, I'd follow the Spring JDBC template model and introduce a RowMapper interface. Let each type of object tell you how to manage it.

Or, better yet, just use Spring JDBC template. They wrote better code than you or I ever will. Hard to top it for simplicity.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top