1

I'm trying to write simple DAO that will create entity objects based on their type stored in String field. How to return type that is changed dynamicly? Method findById() of UserDAO class should return User class object. Same method for ProductDAO should return Product. I don't want to implement findById in every class that extends DAO, it should be done automatically.

Example code:

class DAO {
   protected String entityClass = "";
   public (???) findById(int id) {
      // some DB query
      return (???)EntityFromDatabase; // how to do this?
   }
}
class UserDAO extends DAO {
   protected String entityClass = "User";
}
class ProductDAO extends DAO {
   protected String entityClass = "Product";
}
class User extends Entity {
   public int id;
   public String name;
}
Adeel Ansari
  • 38,068
  • 12
  • 89
  • 127
Matthias
  • 439
  • 1
  • 5
  • 15

4 Answers4

2

Modify it to

class DAO<T> {
   //   protected String entityClass = "";
   public T findById(int id) {

      return (T)EntityFromDatabase; // how to do this?
   }
}
class UserDAO extends DAO<User> {
   //protected String entityClass = "User";
}
class ProductDAO extends DAO<Product> {
   //protected String entityClass = "Product";
}
class User extends Entity {
   public int id;
   public String name;
}
jmj
  • 225,392
  • 41
  • 383
  • 426
2

Use Generics in java. Find an example here.

public interface GenericDAO<T,PK extends Serializable> {

  PK create(T entity);
  T read(PK id);
  void update(T entity);
  void delete(T entity);
}
public class GenericDAOImpl<T,PK extends Serializable>  implements GenericDAO<T,PK>{
    private Class<T> entityType;
    public GenericDAOImpl(Class<T> entityType){
          this.entityType = entityType; 
    }
     //Other impl methods here...
}
chedine
  • 2,364
  • 3
  • 17
  • 24
0

Firstly, instead of using the String, use the class. Next up, use an entityManager (see docs)

class DAO<T> {
   private Class<T> entityClass;

   // How you get one of these depends on the framework.
   private EntityManager entityManager;

   public T findById(int id) {
       return em.find(entityClass, id);
   }
}

Now you can use a different DAO dependent on the type e.g.

DAO<User> userDAO = new DAO<User>();
DAO<Product> userDAO = new DAO<Product>();
Jeff Foster
  • 40,078
  • 10
  • 78
  • 103
0

I strongly recommend you this article, Don't Repeat the DAO. And I must say, you are not having a bad idea.

Adeel Ansari
  • 38,068
  • 12
  • 89
  • 127