Spring Boot 自定义存储库和规范

z4iuyo4d  于 2023-02-16  发布在  Spring
关注(0)|答案(1)|浏览(194)

在 Spring Boot 3中,我创建了一个自定义存储库

@Repository
public class BookRepositoryCustomImpl  implements BookRepositoryCustom  {
}

public interface BookRepositoryCustom  {
      List<Book> searchBook(SearchBook searchBook);
}

@Repository
@Transactional(readOnly = true)
public interface BookRepository extends JpaRepository<Book, Long> {
}

我在searchBook方法中搜索使用规范
用spring 2.x编辑是可能的

@Repository
public class AirportRepositoryImpl extends SimpleJpaRepository<Airport, Integer>
        implements AirportRepositoryCustom {

    @Autowired
    public AirportRepositoryImpl(EntityManager em) {
        super(Airport.class, em);
    }

    @Override
    public Page<Airport> advancedSearch(AirportSearch search, Pageable page) {
        Specification<Airport> specification = (Root<Airport> root, CriteriaQuery<?> cq,
                CriteriaBuilder cb) -> {

            Predicate p = cb.conjunction();
            ...

            return p;

        };
        return this.findAll(specification, page);
    }
}
hc8w905p

hc8w905p1#

您不能在自定义方法实现中使用JpaSpecificationExecutor。但是Specification只能从RootCriteriaQueryCriteriaBuilder创建Predicate。您可以将EntityManager注入BookRepositoryCustomImpl,并使用Criteria API创建查询,包括使用Specification中的Predicate

相关问题