javareflectiondaogenericdao

Is it possible to write a simple generic DAO in Java without using reflection?


I am developing a toy data access mechanism in Java 6 (and above). Each model class should have a findById static method that should instantiate an object from the row with the specified id. I have come up with the approach displayed below. Is my approach considered good practice? If not, what could be improved?

The database (MySQL) bootstrap script:

create database test;
create user test identified by 'test';
grant all on test.* to test;
use test;
create table products(id integer,name varchar(10));
insert into products values(1,'led');

The source code:

import java.sql.*;

class Test {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
        Product p = Product.findById(1);
        System.out.println(p.id + " " + p.name);
    }
}

class Database {
    static <T extends Model<T>> T findById(T m, String sql, int id) throws SQLException {
        try (Connection conn = DriverManager.getConnection("jdbc:mysql:///test", "test", "test");
                PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, id);
            try (ResultSet rs = stmt.executeQuery()) {
                rs.next();
                m.load(rs);
            }
        }
        return m;
    }
}

abstract class Model<T> {
    abstract void load(ResultSet rs) throws SQLException;
}

class Product extends Model<Product> {
    int id;
    String name;

    static Product findById(int id) throws SQLException {
        return Database.findById(new Product(), "select * from products where id=?", id);
    }

    @Override
    void load(ResultSet rs) throws SQLException {
        this.id = rs.getInt("id");
        this.name = rs.getString("name");
    }
}

Solution

  • You are mixing concerns and responsibility, introducing tight coupling between your entities (Product) and your data-access layer.

    You should separate

    You may even want to go one step further, and dissociate the DAO layer from the actual repository layer, but that could be seen as premature optimisation, depending on the number of different entity classes you have in your system.

    That has many benefits:

    Also, it's not necessarily a good idea to try to have generic methods everywhere: usually you'll find the findById you want is slightly different for each of your entities, and some of them don't fit the generic method you described in Database (I'm not even mentioning it's a static method, which is a bad smell). In my current team, we use the rule of three: introduce refactored generic classes / method only when you're writing the 3rd elements of your system that would benefit from it. Else we consider it premature optimisation.