Jpa使用Specification分页查询

背景

虽然我很讨厌Jpa但是架不住别人用,那还是要熟悉下的

开始

版本:

  • springboot 2.7.15
  • JDK 11
  • mysql-connector-j 8.1.0

Pom

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.1.0</version>
</dependency>

配置文件

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true
    username: test
    password: test
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
    #打印sql
    show-sql: true

实体类

一方

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
@Table(name = "rule_group", indexes = {@Index(name = "idx_timer",  columnList="create_time")})
public class RuleGroup {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", columnDefinition = "BIGINT NOT NULL AUTO_INCREMENT COMMENT '自增ID'")
    private Long id;

    @Column(name = "group_name", unique = true, nullable = false)
    private String groupName;

    @Column(name = "group_code", unique = true, nullable = false)
    private String groupCode;

    @Column(name = "group_desc", nullable = false, length = 512)
    private String groupDesc;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "rule_group_id")
    private List<Rule> ruleList;

    @Column(name = "create_time", nullable = false)
    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    private Date createTime;

    @Column(name = "update_time", nullable = false)
    @UpdateTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    private Date updateTime;

    @Column(name = "create_by", nullable = false, length = 512)
    private String createBy;

    @Column(name = "update_by", nullable = false, length = 512)
    private String updateBy;

}

多方

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
@Table(name = "rule", indexes = {@Index(name = "idx_timer",  columnList="create_time")})
public class Rule {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", columnDefinition = "BIGINT NOT NULL AUTO_INCREMENT COMMENT '自增ID'")
    private Long id;

    @Column(name = "rule_group_id", columnDefinition = "bigint(20) NOT NULL DEFAULT '0' COMMENT '规则组ID'")
    private Long ruleGroupId;

    @Column(name = "rule_name", unique = true, nullable = false)
    private String ruleName;

    @Column(name = "rule_code", unique = true, nullable = false)
    private String ruleCode;

    @Column(name = "rule_desc", unique = true, nullable = false)
    private String ruleDesc;

    @Column(name = "create_time", nullable = false)
    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    private Date createTime;

    @Column(name = "update_time", nullable = false)
    @UpdateTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    private Date updateTime;

    @Column(name = "create_by", nullable = false, length = 512)
    private String createBy;

    @Column(name = "update_by", nullable = false, length = 512)
    private String updateBy;
}

RuleDao

@Repository
public interface RuleDao extends JpaRepository<Rule, Long>, JpaSpecificationExecutor<Rule> {
}

RuleGroupDao

@Repository
public interface RuleGroupDao extends JpaRepository<RuleGroup, Long>, JpaSpecificationExecutor<RuleGroup> {
}

服务层使用

@Resource
private RuleDao ruleDao;

@Resource
private RuleGroupDao ruleGroupDao;


@Override
public Page<Rule> searchRule(SearchRulesVo vo) {
    return ruleDao.findAll((Specification<Rule>) (root, query, cb) -> {
        List<Predicate> predicates = predicatesRule(root, cb, vo);
        Predicate[] pre = new Predicate[predicates.size()];
        return cb.and(predicates.toArray(pre));
    }, PageRequest.of(vo.getPage() - 1, vo.getSize(), Sort.by(Sort.Direction.DESC, "createTime")));
}

private List<Predicate> predicatesRule(Root<Rule> root, CriteriaBuilder cb, SearchRulesVo vo) {
    List<Predicate> pres = new ArrayList<>();

    if (Objects.nonNull(vo.getRuleId()) && vo.getRuleId() > 0) {
        pres.add(cb.equal(root.get("id"), vo.getRuleId()));
    } else if (Objects.nonNull(vo.getRuleIdList()) && vo.getRuleIdList().size() > 0) {
        pres.add(root.get("id").in(vo.getRuleIdList()));
    }

    if (Objects.nonNull(vo.getRuleGroupId()) && vo.getRuleGroupId() > 0) {
        pres.add(cb.equal(root.get("ruleGroupId"), vo.getRuleGroupId()));
    } else if (Objects.nonNull(vo.getRuleGroupIdList()) && vo.getRuleGroupIdList().size() > 0) {
        pres.add(root.get("ruleGroupId").in(vo.getRuleGroupIdList()));
    }

    if (StringUtils.hasText(vo.getRuleName())) {
        pres.add(cb.like(root.get("ruleName"), "%" + vo.getRuleName() + "%"));
    }

    if (StringUtils.hasText(vo.getRuleCode())) {
        pres.add(cb.equal(root.get("ruleCode"), vo.getRuleCode()));
    }

    return pres;
}

@Override
public Page<RuleGroup> searchRuleGroup(SearchRulesVo vo) {
    return ruleGroupDao.findAll((Specification<RuleGroup>) (root, query, cb) -> {
        List<Predicate> predicates = predicatesRuleGroup(root, cb, vo);
        Predicate[] pre = new Predicate[predicates.size()];
        return cb.and(predicates.toArray(pre));
    }, PageRequest.of(vo.getPage() - 1, vo.getSize(), Sort.by(Sort.Direction.DESC, "createTime")));
}

private List<Predicate> predicatesRuleGroup(Root<RuleGroup> root, CriteriaBuilder cb, SearchRulesVo vo) {
    List<Predicate> pres = new ArrayList<>();
    if (Objects.nonNull(vo.getRuleGroupId()) && vo.getRuleGroupId() > 0) {
        pres.add(cb.equal(root.get("id"), vo.getRuleGroupId()));
    } else if (Objects.nonNull(vo.getRuleGroupIdList()) && vo.getRuleGroupIdList().size() > 0) {
        pres.add(root.get("id").in(vo.getRuleGroupIdList()));
    }
    if (StringUtils.hasText(vo.getRuleGroupName())) {
        pres.add(cb.like(root.get("groupName"), "%" + vo.getRuleGroupName() + "%"));
    }
    if (StringUtils.hasText(vo.getRuleGroupCode())) {
        pres.add(cb.equal(root.get("groupCode"), vo.getRuleGroupCode()));
    }
    return pres;
}

cb提供了常用的where拟合函数,蛮好用的,整体也不复杂
就这样

使用`Specification`实现CLOB数据的模糊查询,需要创建一个实现了`Specification`接口的类,并在其中实现`toPredicate()`方法。下面给出一个示例: ``` public class MyEntitySpecifications { public static Specification<MyEntity> clobDataContains(String keyword) { return (root, query, builder) -> { Expression<String> clobData = builder.function("to_clob", String.class, root.get("clobData")); return builder.like(builder.lower(clobData), "%" + keyword.toLowerCase() + "%"); }; } } ``` 在这个示例中,我们使用了`to_clob()`函数将CLOB数据转换为字符串,然后使用`like()`方法进行模糊匹配。注意,我们将搜索关键字转换为小写字母,以便不区分大小写地进行匹配。 然后,我们可以在`MyEntityRepository`接口中定义一个名为`findAllByClobDataContaining()`的方法,该方法接受一个`String`类型的参数`keyword`,并使用`MyEntitySpecifications.clobDataContains()`方法创建一个`Specification`对象进行查询: ``` public interface MyEntityRepository extends JpaRepository<MyEntity, Long>, JpaSpecificationExecutor<MyEntity> { List<MyEntity> findAllByClobDataContaining(String keyword, Pageable pageable); } ``` 在这个方法中,我们使用了`findAll()`方法的分页版本,并将`Specification`对象作为参数传递给它。 最后,在调用该方法时,我们可以像下面这样传递搜索关键字和分页参数: ``` Pageable pageable = PageRequest.of(0, 10); List<MyEntity> result = myEntityRepository.findAllByClobDataContaining("keyword", pageable); ``` 这样就可以使用`Specification`实现CLOB数据的模糊查询了。需要注意的是,`to_clob()`函数的具体实现可能因数据库类型而异,需要根据实际情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值