javaspringdaospring-4genericdao

Autowiring generic types with constructor [Spring 4.2.5]


I'm new to Spring and trying to implement Generic DAO like in this article http://www.ibm.com/developerworks/library/j-genericdao/ . I have couple of entities - ConcreteEntity1 and ConcreteEntity2. Also, I have classes

public interface GenericDao<T extends Serializable>  {
    public T get(long id);
    public List<T> get(String hql);
    public void remove(T persistentObject);
    public void add(T entity);
}

and

@Repository("hibGenericDao")
public class HibGenericDaoImpl<T extends Serializable> implements GenericDao<T> {

    @Autowired
    private SessionFactory sessionFactory;

    private Class<T> type;

    public HibGenericDaoImpl(Class<T> type) {
        this.type = type;
    }

    /** {@inheritDoc} */
    @Override
    public T get(long id) {
        T entity;
        try (Session session = sessionFactory.getCurrentSession()) {
            entity = session.get(type, id);
        }
        return entity;
    }

    /** {@inheritDoc} */
    @Override
    public List<T> get(String hql) {
        List<T> entityList;
        try (Session session = sessionFactory.getCurrentSession()) {
            Query query = session.createQuery(hql);
            entityList = query.list();
        }
        return entityList;
    }

    /** {@inheritDoc} */
    @Override
    public void remove(T persistentObject) {
        try (Session session = sessionFactory.getCurrentSession()) {
            session.delete(persistentObject);
        }
    }

    /** {@inheritDoc} */
    @Override
    public void add(T entity) {
        try (Session session = sessionFactory.getCurrentSession()) {
            session.saveOrUpdate(entity);
        }
    }
}

Now I'm trying to write service layer, and I want to autowire HibGenericDaoImpl<ConcreteEntity1> where field type contains ConcreteEntity1.class. Could you please say how to perform it without XML?


Solution

  • If you are already using spring, you can use the GenericTypeResolver utility class, as shown in this SO answer: How to get a class instance of generics type T

    You should be able to do something like:

     this.type = (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), GenericDao.class);