1

In the below Service I'm trying to init my Dao and inject the EntityManager into it. We're not using spring for this project. My IDE is complaining about calling setEntityManager() because it can't recognize that the object is always a GenericDao. Is this the proper way to do this?

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());
        }
    }
}

1 Answer 1

2

You could use a cast:

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

But I think if you know it's always a GenericDao, why not just make it that type to begin with, e.g.

protected GenericDao dao;

And change the class declaration as well:

public class GenericService<T, GenericDao>
1
  • 1
    Good call... what I needed was public class GenericService<T, Dao extends GenericDao> {
    – Ben
    Feb 18, 2013 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.