2011-07-21 36 views
1

我想写一个简单的DAO,它将根据存储在String字段中的类型创建实体对象。如何返回动态更改的类型? UserDAO类的方法findById()应返回User类对象。 ProductDAO的相同方法应该返回Product。 我不想在每个扩展DAO的类中实现findById,它应该自动完成。Java DAO工厂动态返回对象类型

示例代码:

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

回答

2

其修改为

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

它的工作原理,谢谢! – Matthias

+0

欢迎您:) –

0

首先,而不是使用String,使用类。接下来,使用entityManager(见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); 
    } 
} 

现在你可以使用一个不同的DAO依赖于类型例如

DAO<User> userDAO = new DAO<User>(); 
DAO<Product> userDAO = new DAO<Product>(); 
+0

如何在DAO中获得'entityClass'? – duckegg

2

使用Generics in java。在这里找到一个例子。

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