1

For legacy and other reasons I'm not able to use JPA repositories. So I'm trying to build something similar for a project. I have class MyEntityRepo

@Repository
public class MyEntityRepo extends CustomRepository<MyEntity, Integer> {

}

And

public abstract class CustomRepository<T, ID> {

    private static final Logger LOG =LoggerFactory.getLogger(CustomRepository.class);

    protected SessionFactory sessionFactory;

    private T _clazz;
    private String className;

    public CustomRepository() {             
        String className = _clazz.getClass().getName();
        if (className.contains(".")) {
            className = className.substring(className.lastIndexOf('.') + 1);
        }
        LOG.info("classname:{}", className);
    }
}

But when I'm starting the project, the spring framework is not able to create the bean as it is giving NullPointerException because _clazz field is null. Can somebody please explain how to achieve this?

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29

2 Answers2

0

As far as I understand the main problem is to get generic class.

You don't need to store T _clazz;

Try to use org.springframework.core.GenericTypeResolver

_clazz = (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), CustomRepository.class);

got the logic from the second answer

But actually Spring Data creates proxy from interface on fly. See the example

StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • order of answers in SOF isn't maintained, it's better to directly link the answer instead of linking the question if you want to refer a specific answer. – Ram Patra Feb 05 '18 at 23:40
0

I got one more way which Hibernate uses.

    private Class<T> _clazz;
    private String className;
    public LybrateRepository() {
        this._clazz = (Class<T>) ((ParameterizedType) getClass()
                                .getGenericSuperclass()).getActualTypeArguments()[0];
        String className = _clazz.getName();
        if (className.contains(".")) {
            className = className.substring(className.lastIndexOf('.') + 1);
        }
        LOG.info("classname:{}", className);
     }

This is working for me :)