【发布时间】:2013-08-09 05:14:51
【问题描述】:
根据 Spring Data Commons documentation,将自定义方法实现添加到 Spring Data 存储库非常简单:
interface UserRepositoryCustom {
public void someCustomMethod(User user);
}
class UserRepositoryCustomImpl implements UserRepositoryCustom {
public void someCustomMethod(User user) {
// Your custom implementation
}
}
public interface UserRepository extends JpaRepository<User, Long>,
UserRepositoryCustom {
}
但是,我想不通的是,如果你想使用类型参数怎么办?例如:
interface SearchableRepository<T> {
public Page<T> search(String query, Pageable page);
}
class SearchableRepositoryImpl<T> implements SearchableRepository<T> {
public Page<T> search(String query, Pageable page) {
// Right here, I need the Class<T> of T so that I can create
// the JPA query
}
}
public interface UserRepository extends JpaRepository<User, Long>,
SearchableRepository<User> {
}
public interface NewsRepository extends JpaRepository<Article, Long>,
SearchableRepository<Article> {
}
在该search 方法的实现中,我需要知道提供的类型参数T 的Class<T>,以便我可以创建JPA 查询。我不想add custom behavior to all repositories,因为我不希望所有存储库都是可搜索的。我只想应用SearchableRepository接口来选择仓库。
那么你怎么能做到这一点?或者你能做到吗?
【问题讨论】:
标签: java spring repository spring-data spring-data-jpa