我有一个数据库,其中包含多个表和相应的表格数据对象。对于(几乎)所有表,我有一个Model类,用于处理与相应表的交互(添加记录,获取数据并实例化一个包含数据的对象)如何从数据库中获取的数据通用构造对象
所有Model类都有一个getById(int id)
方法,所以我认为它将它放在一个超类(CoreModel)中是很好的
但是这里的东西: 由于Model类只是一种交互层,所以我认为我没有用它来创建一个实例。使类最终,它的方法是静态的,但然后问题出现super()方法不能从静态方法调用。
我的问题:这通常如何完成?我对面向对象很陌生,并且对整个多态性事物感到困惑。是否有任何设计模式或标准解决方案以通用方式解决此问题?
示例代码:
public final class CoreModel {
public static ResultSet getById(int id, String table){
Statement stat = null;
ResultSet res = null;
try {
stat = DatabaseModel.getStatement();
res = stat.executeQuery("SELECT * FROM `"+table+"` WHERE `id` = " +id);
res.next();
stat.close();
res.close();
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
return res;
}
}
public final class PersonModel extends CoreModel {
public static Person getById(int id) {
ResultSet personResult = super.getById(id, "person");
// instatiate Person object
return personObj;
}
}