2011-07-21 35 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... 
}