在下面的服务中,我试图初始化我的 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());
}
}
}