I have a database with multiple tables and corresponding objects for the table's data. For (almost) all tables I have a Model class, which handle the interaction with it's corresponding table (adding records, fetching data and instantiate an object holding the data.
All Model classes have a getById(int id)
method, so I thought it would be nice to put it in a superclass (CoreModel).
But here the thing: Since the Model classes are just a sort of interaction layers, I see no use in creating an instance of it. So I thought I make the class final and it's methods static, but then the problem arises that super() methods cannot be called from static methods.
My question: How is this usually done? I'm sorta new to OOP and am pretty baffled by the whole polymorphism thing. Are there any design patterns or standard solutions to solve this problem in a generic way?
Example code:
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;
}
}