Matthias
Matthias

Reputation: 453

Java DAO factory dynamic returned object type

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;
}

Upvotes: 1

Views: 3236

Answers (3)

chedine
chedine

Reputation: 2374

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...
}

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240976

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;
}

Upvotes: 2

Jeff Foster
Jeff Foster

Reputation: 44746

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>();

Upvotes: 0

Related Questions