Spring 4.0: Resolve Type of GenericDao

I updated my Spring MVC environment to Version 4.0.0.RELEASE. After reading this article (https://spring.io/blog/2013/12/03/spring-framework-4-0-and-java-generics), I tried to use the new generics support, to autowire my GenericDAOs.

Spring 3.2

In Spring 3.2 environment I created for each DAO instance a separate bean and passed the class as paramameter to constructor. This because as I am aware, it is not possible to resolve a generic type at runtime.

@Bean
public GenericDaoImpl<Permission, Integer> permissionDao() {
    return new GenericDaoImpl<Employee, Integer>(Employee.class, sessionFactory); 
}

Spring 4.0.0.RELEASE

With spring 4.0 I just have to autowire my GenericDAO in Service like:

@Autowired private GenericDaoImpl<Employee, Integer> employeeDao;

And within GenericDAOImpl:

@Repository
public class GenericDaoImpl<T, PK extends Serializable> implements GenericDao<T, Serializable> {

        @Autowired
        private SessionFactory sessionFactory;
        private Class<?> genericType;

This solution is much easier and does work for most of my DAO methods. But for a few of them I need to know which type my GenericDAO instance has.

@Override
public List<T> findAll() {
    return getCurrentSession().createQuery("FROM " + getGenericType().getName()).list();
}

So I tried to resolve the type with the static methods of GenericTypeResolver and ResolvableType. But I am not able to resolve the type. Is this still not possible?

Thanks in advance.

UPDATE:

private Class<T> getGenericType() {
    return (Class<T>) GenericTypeResolver.resolveTypeArgument(GenericDaoImpl.class, GenericDao.class);
}

Answers


private Class<T> getGenericType() {
    return (Class<T>) GenericTypeResolver.resolveTypeArgument(GenericDaoImpl.class, GenericDao.class);
}

Your GenericDaoImpl doesn't have a type associated as it is generic, it will not resolve to a proper type.

Instead of passing in the GenericDaoImpl.class you should call getClass() and pass that in, because you want to know the type of the current instance

private Class<T> getGenericType() {
    return (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), GenericDao.class);
}

Something like that.


Need Your Help

std::string crashing while iterating on mySQL connector query results

c++ mysql string crash std

I'm trying to get a std::string from my database using mysql connexion

Return Object by value in Javascript

javascript object pass-by-reference creation

I know that Objects in Javascript are passed by reference, but is there any way to return object as values.