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");
}
}