1

在下面的服务中,我试图初始化我的 Dao 并将 EntityManager 注入其中。我们没有在这个项目中使用 spring。我的 IDE 抱怨调用setEntityManager(),因为它无法识别该对象始终是GenericDao. 这是正确的方法吗?

public class GenericService<T, Dao> {

    private static Logger logger = Logger.getLogger(Logger.class.getName());

    protected Dao dao;
    protected EntityManager em;

    public GenericService(Class<Dao> daoClass) {
        try {
            dao = daoClass.newInstance();

            EntityManagerFactory emf = Persistence.createEntityManagerFactory("unit");
            em = emf.createEntityManager();

            dao.setEntityManager(em);

        } catch(InstantiationException e) {
            logger.log(Level.SEVERE, "Unable to initialize DAO: {1}", daoClass.getClass());
        } catch(IllegalAccessException e) {
            logger.log(Level.SEVERE, "Unable to initialize DAO: {1}", daoClass.getClass());
        }
    }
}
4

1 回答 1

2

您可以使用演员表:

((GenericDao)dao).setEntityManager(em);

但我想如果你知道它总是一个 GenericDao,为什么不把它作为开始的类型,例如

protected GenericDao dao;

并更改类声明:

public class GenericService<T, GenericDao>
于 2013-02-18T20:44:09.830 回答