Java 6 (およびそれ以降) でおもちゃのデータ アクセス メカニズムを開発しています。各モデル クラスにはfindById
、指定された ID を持つ行からオブジェクトをインスタンス化する静的メソッドが必要です。以下に示すアプローチを思いつきました。私のアプローチは良い習慣と見なされますか? そうでない場合、何を改善できますか?
データベース (MySQL) ブートストラップ スクリプト:
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');
ソースコード:
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");
}
}