【发布时间】:2017-06-27 01:39:06
【问题描述】:
需要在存储库层进行自定义动态搜索。无法通过查询方法或通过查询注释进行查询。 这个动态搜索需要调用pleJpaRepository spring类实现的findAll(Specification, Paging)
public interface CardsRepositoryCustom {
public Page<Cards> customSearch(CardSearch CardSearch, Pageable page);
}
public interface CardsRepository extends JpaRepository<Cards, Integer>, CardsRepositoryCustom {
}
@Repository
public class CardsRepositoryImpl extends SimpleJpaRepository implements CardsRepositoryCustom{
public CardsRepositoryImpl(Class<Cards> domainClass, EntityManager em) {
super(domainClass, em);
}
@PersistenceContext
private EntityManager em;
@Override
public Page<Cards> customSearch(CardSearch CardSearch, Pageable page) {
Specification<Cards> specification = (Root<Cards> root, CriteriaQuery<?> cq, CriteriaBuilder cb) -> {
..
}
return this.findAll(specification, page);
}
}
@Service
public class CardsServiceImpl implements CardsService {
@Autowired
public CardsServiceImpl(CardsRepository CardsRepository) {
this.CardsRepository = CardsRepository;
}
public CardsRepository CardsRepository;
@Override
public Page<Cards> customSearch(CardSearch CardSearch, Pageable page) {
...
return CardsRepository.customSearch(CardSearch, page);
}
...
}
当我运行应用程序时,我得到了
com.dwengo.cards.repository.CardsRepositoryImpl 中构造函数的参数0 需要
【问题讨论】:
-
CardsRepositoryImpl 构造函数的第一个参数没有用,因为 Class
只能通过 Cards.class 获得。所以调用super时直接使用Cards.class。 -
无任何更改 com.dwengo.cards.repository.CardsRepositoryImpl 中构造函数的参数 0 需要一个找不到的“java.lang.Class”类型的 bean。
-
所以你没有从定义中删除它......你需要在构造函数上设置自动装配。
-
当我们扩展 SimpleJpaRepository 类时,我们可以选择两个构造函数:(JpaEntityInformation
entityInformation, EntityManager entityManager) 或 (Class domainClass, EntityManager em) 和 @Autowired public CardsRepositoryImpl(类 domainClass, EntityManager em) { super(Cards.class, em); } 不起作用 -
不指定类,只做 super(MyDomain.class, em);