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

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

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

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

转自 https://lingkang.top/archives/jpa-shi-xian-fu-ze-cha-xun

依赖

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-securityartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>com.mysqlgroupId>
            <artifactId>mysql-connector-jartifactId>
            <scope>runtimescope>
        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) {
        // 分页
        PageRequest pageRequest = PageRequest.of(page, size);
        ClassifyEntity classifyEntity = new ClassifyEntity();
        ExampleMatcher matcher = ExampleMatcher.matching();

        // 不为空时启用模糊搜索
        if (StrUtil.isNotBlank(search)) {
            // 要搜索的字段
            classifyEntity.setName(search);
            // 前、后匹配即 %search%,name对应的是实体name,配合上面的 classifyEntity.setName(search);
            matcher.withMatcher("name", match -> match.endsWith())
                    .withMatcher("name", match -> match.startsWith());
        }

        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()); // 查询内容
    }

你可能感兴趣的:(java,java,jpa,spring,boot,hibernate)