I have a Java database application using hibernate, with different Classes that have the same attributes (here: “active”). In an interface, there is a function that retrieves entries from a database based on such an attribute (active). So far, I was doing this:
//interface
public interface ObjIntf {
default <Entity> ArrayList<Entity> get(Boolean active);
}
//implementation 1
public class ObjCar implements ObjIntf {
@SuppressWarnings("unchecked")
@Override
public ArrayList< ObjCar > get(Boolean active) {
@SuppressWarnings("rawtypes")
Query query = DB.s.createQuery("from " + ObjCar.class.getSimpleName() + " where active = :active");
query.setParameter("active", active);
if (!query.list().isEmpty()) {
return (ArrayList< ObjCar >) query.list();
} else {
return null;
}
}
//implementation 1
public class ObjPerson implements ObjIntf {
@SuppressWarnings("unchecked")
@Override
public ArrayList< ObjPerson > get(Boolean active) {
@SuppressWarnings("rawtypes")
Query query = DB.s.createQuery("from " + ObjPerson.class.getSimpleName() + " where active = :active");
query.setParameter("active ", active);
if (!query.list().isEmpty()) {
return (ArrayList< ObjPerson >) query.list();
} else {
return null;
}
}
As You can see, there is a lot of redundant code in each implementing class, which I would like to avoid. What I would like instead therefore, is to have a generic default function in the interface, which will return the same for each implementation of the interface (unless overridden by the implementing class of course). I.e., something like this (except this does not work, of course):
public interface EnumSvcIntf {
default <Entity> ArrayList<Entity> get(Boolean active) {
@SuppressWarnings("rawtypes")
Query query = DB.s.createQuery("from " + Entity.class.getSimpleName() + " where active = :active");
query.setParameter("active", "+");
return (ArrayList<Entity>) query.list();
}
}
I am lacking the proper understanding here, how to create the function in the interface in the right way, to be able to use it in different contexts/ different classes.
How can I adjust the function in the interface instead to make this happen?
Aucun commentaire:
Enregistrer un commentaire