I have a class which does operations on the database, but I want to keep it as general and abstract as possible, thus by Object return types.
Here’s an example method of that class:
public static List<Object> getAll(String table) throws HibernateException{
Session sessie = HibernateUtil.getSessionFactory().openSession();
Transaction trans = sessie.beginTransaction();
List<Object> objects = sessie.createSQLQuery("SELECT * FROM " + table + ";").list();
trans.commit();
sessie.close();
return objects;
}
Now I have another class User which should have a a method getAll with a List<User> return type and the implementation of the method is the same.
Is this even possible? I know it isn’t possible to overload methods with different return types. Is this doable with some kind of a design pattern, interface setup?
So basicly I don’t want to do the implementation again, it is already specified in the getAll method which returns an object. I just want to perform that method but with dynamic return types.
The reason I am asking this is because I don’t want to do the following somewhere else in my code:
User user = new User(...);
// this should be user.getAll() and the type of that method should be an User, not an object
(User)user.getAll()
The reason I am doing it this way is because I can have other tables in the future whom would be able to call the getAll method but get a cast object back as return type and not the type object.
I am looking at the cleanest and best OO solution, even if it means that I need to restructure my code.
If you really need it you can make your class generic with returned type as generic type parameter, so you can have:
and then do
It’s ugly though as you pass the name of the table as a parameter. You should probably rethink your data access layer design .
edit:
Ok to make it clearer:
and then you can call it like
You could put a static field in in every class extending GenericDAOAndModelClass to represent table name, so that you don’t have to pass the parameter to getAll and getOne.