I know this question has been asked often but I'm unable to find a solution. How can I get a generic type class name in a Spring injected repository?
Here it is my base repository
{
command: ["edit", "destroy"],
title: " ",
width: 120
}],
editable: "inline"
this is the interface
public interface UserRepository extends JpaRepository<User, Long>, IUserRepository<User>{
User findByUsername(String username);
}
and finally here it is the implementation
public interface IUserRepository<T> {
public List<T> findAllValidEtSiteAndStructure();
}
how can I get type.name? Thanks in advance
答案 0 :(得分:2)
您的问题的一般答案可以在文档中看到 - &gt; “Spring Data存储库的自定义实现”一章中的http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations
但我认为在你的情况下这不应该是必要的。你应该能够以下面的方式做到这一点。
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
List<User> findByStructureAndSiteAndValid(Structure structure, Site site, boolean valid);
}
答案 1 :(得分:2)
基本上,由于type erasure,您无法获得泛型类型。
我要做的是向// this means you want to draw a line on the outer edge
// 1 is thickness, and you got more options like color, etc.
graphics.lineStyle(1);
// draw rect
graphics.drawRect(x, y, width, height);
// draw circle
graphics.drawCircle(x, y, radius);
添加一个返回相关类型的抽象方法:
UserRepositoryImpl
然后我将为public abstract Class getType();
创建特定的实例,在编译时已知该类型。例如:
UserRepositoryImpl
答案 2 :(得分:1)
考虑到您正在使用Spring Framework,请使用下面的代码片段,我已经过测试,它运行得很好:
ResolvableType resolvableType = ResolvableType.forClass(UserRepository.class).as(JpaRepository.class);
System.out.println(resolvableType.getGeneric(0));//User
System.out.println(resolvableType.getGeneric(1));//Long