我知道这个问题经常被问到,但我找不到解决方法。在Spring注入的存储库中,如何获取通用类型类名?
这是我的基本存储库:
public interface UserRepository extends JpaRepository<User, Long>, IUserRepository<User>{
User findByUsername(String username);
}
这是接口。
public interface IUserRepository<T> {
public List<T> findAllValidEtSiteAndStructure();
}
最终,这就是实现过程
public class UserRepositoryImpl<T> implements IUserRepository<T> {
@PersistenceContext
private EntityManager em;
private Class< T > type;
@Override
public List<T> findAllValidEtSiteAndStructure() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof UserAuthentication) {
final User currentUser = ((UserAuthentication) authentication).getDetails();
return (List<T>) em.createQuery("FROM " + type.getName()+ " WHERE site=:site AND structure=:structure AND valid=:valid")
.setParameter("site", currentUser.getInstallation().getSite())
.setParameter("structure", currentUser.getInstallation().getStructure())
.setParameter("valid", true)
.getResultList();
}
return null;
}
}
如何获取type.name?
谢谢您的提问。