1

String フィールドに格納されている型に基づいてエンティティ オブジェクトを作成する単純な DAO を作成しようとしています。動的に変更された型を返す方法は? 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 で Generics を使用します。ここで例を見つけてください。

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

この記事Don't Repeat the DAOを強くお勧めします。そして、私は言わなければなりません、あなたは悪い考えを持っていません.

于 2011-07-21T09:45:34.610 に答える
0

まず、 を使用する代わりにString、 クラスを使用します。次に、entityManagerdocsを参照)を使用します

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 に答える