1

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

示例代码:

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

4 回答 4

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;
}
于 2011-07-21T09:34:03.107 回答
2

在 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...
}
于 2011-07-21T09:36:39.040 回答
0

首先,不要使用 ,而是String使用类。接下来,使用entityManager(参见文档

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>();
于 2011-07-21T09:33:38.833 回答
0

我强烈推荐你这篇文章,不要重复 DAO。我必须说,你的想法不错。

于 2011-07-21T09:45:34.610 回答