spring-boot-data-jpa、JPA实现复杂查询、复杂搜索

JPA越来越丰富了,下面使用springboot3.x实现JPA分页

通过传入Example参数实现复杂字段查询

依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency> 

数据库配置

spring.jpa.show-sql=true
spring.jpa.open-in-view=false
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&nullCatalogMeansCurrent=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.poolName=db1

启动类

@SpringBootApplication
@EnableJpaRepositories("top.lingkang.lingdongmall.repository")
@EntityScan("top.lingkang.lingdongmall.entity")
public class LingdongMallApplication {

    public static void main(String[] args) {
        SpringApplication.run(LingdongMallApplication.class, args);
    }

}

接口

/**
 * @author lingkang
 * created by 2023/12/12
 */
public interface ClassifyRepository extends JpaRepository<ClassifyEntity, String> {
}

调用

    public ResponseResultPage list(String level, String search, Integer page, Integer size) {
        // 分页,注意,page分页是从0开始计算的,0=第一页
        PageRequest pageRequest = PageRequest.of(page, size);
        ClassifyEntity classifyEntity = new ClassifyEntity();
        // 提前设置要过滤的方式  前、后匹配即 %search%,name对应的是实体name,配合下面的 classifyEntity.setName(search); 为空时不会进行模糊搜索。也可以使用match.contains(),它是 %search%
        ExampleMatcher matcher = ExampleMatcher.matching()
        			.withMatcher("name", match -> match.endsWith())
                    .withMatcher("name", match -> match.startsWith());

        // 不为空时启用模糊搜索
        if (StrUtil.isNotBlank(search)) {
            // 要搜索的字段
            classifyEntity.setName(search);
        }

        Example<ClassifyEntity> example = Example.of(classifyEntity, matcher);
        Page<ClassifyEntity> all = classifyRepository.findAll(example, pageRequest);
        return new ResponseResultPage()
                .setPage(page)
                .setSize(size)
                .setTotal(all.getTotalElements()) // 分页总数
                .setData(all.getContent()); // 查询内容
    }