spring data jpa

1. 过滤数据 ,使用specification-arg-resolver 条件查询
2. jpa 关键字

过滤数据 ,使用specification-arg-resolver 条件查询

jpa specification 数据过滤器:
添加maven依赖

net.kaczmarzyk
specification-arg-resolver
0.6.1

在mvc配置类里面配置参数解析:(不配置参数解析不能接收到参数)

@Override 
public void addArgumentResolvers( MutableList argumentResolvers) {
    argumentResolvers.add(new SpecificationArgumentResolver())
  }

使用

@RequestMapping("/customers")
public Object findByName(
        @And({
            @Spec(path="registrationDate", params="registeredBefore", spec=DateBefore.class),
            @Spec(path="lastName", spec=Like.class)}) Specification customerSpec) {

    return customerRepo.findAll(customerSpec);
}

url:[GET http://myhost/customers?registeredBefore=2015-01-18&lastName=Simpson](GET http://myhost/customers?registeredBefore=2015-01-18&lastName=Simpson)

生成sql: select c from Customer c where c.registrationDate < :registeredBefore and c.lastName like '%Simpson%'

关联查询:
model 里面配置


@ApiModelProperty("用户id")
    @JsonIgnore
    @JoinColumn(name = "member_id", foreignKey = ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT))
    @OneToOne(fetch = FetchType.LAZY, targetEntity = Member::class)
    @NotFound(action = NotFoundAction.IGNORE)
    val member: Member? = null,

关联表字段 在controller层过滤

 @GetMapping
  @ApiOperation(value = "会员列表", response = MiningTeamVo::class, responseContainer = "List")
  @ApiImplicitParams(
      ApiImplicitParam(name = "name", value = "团队名称", paramType = "query", dataType = "string"),
      ApiImplicitParam(name = "number", value = "团队编号", paramType = "query", dataType = "string"),
      ApiImplicitParam(name = "usr", value = "用户名", paramType = "query", dataType = "string"),
      ApiImplicitParam(name = "invitationCode", value = "邀请码", paramType = "query", dataType = "string"),
      ApiImplicitParam(name = "startDate", value = "创建起始时间", paramType = "query", dataType = "long"),
      ApiImplicitParam(name = "endDate", value = "创建截止时间", paramType = "query", dataType = "long")
  )
  fun page(
      @Joins(fetch = [JoinFetch(paths = ["member"])])//关联表
      @And(
          Spec(path = "name", spec = Like::class),
          Spec(path = "number", spec = Equal::class),
          Spec(path = "invitationCode", spec = Like::class),
          Spec(path = "createdAt", params = ["startDate"], spec = GreaterThanOrEqual::class),
          Spec(path = "createdAt", params = ["endDate"], spec = LessThanOrEqual::class),
          Spec(path = "member.usr", params = ["usr"], spec = Like::class)//查询关联表字段
      )

jpa动态条件条件查询:

//定义动态条件
  private fun getMemberSpec(teamId: Long, nickName: String?): Specification {
    return Specification.where { root, query, cb ->
      val predicates = arrayListOf()
      if (StringUtils.isNotBlank(nickName))
        predicates.add(cb.like(root.get("nickName").`as`(String::class.java), "%" + nickName + "%"))
      predicates.add(cb.equal(root.get("teamId"), teamId))
      predicates.add(cb.equal(root.get("status"), 1))
      query.where(* predicates.toTypedArray()).groupRestriction
    }
  }
//作为参数使用
 poPage =miningTeamMemberRepository.findAll(getMiningTeamMemberSpec(it.get().teamId, nickName), pageable!!)

specification使用and可以合并连接两个specification条件
getMemberSpec().and(specification)
需要注意的是:
query.where(* predicates.toTypedArray()).groupRestriction
下面两个转换是有区别的
.groupRestriction-->Predicate getGroupRestriction() 使用and 合并回失败需要使用 .restriction-->Predicate getRestriction()

Spring Data Jpa 查询关键字

关键字 转载自
作者:爱吃肉的唐长老
链接:https://www.jianshu.com/p/22e0c7a20eff

find可以换成count、delete、get等等

关键字 示例 同功能JPQL
And findByLastnameAndFirstname where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstname,findByFirstnameIs,findByFirstnameEquals where x.firstname = 1?
Between findByStartDateBetween where x.startDate between 1? and ?2
LessThan findByAgeLessThan where x.age < ?1
LessThanEqual findByAgeLessThanEqual where x.age <= ?1
GreaterThan findByAgeGreaterThan where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual where x.age >= ?1
After findByStartDateAfter where x.startDate > ?1
Before findByStartDateBefore where x.startDate < ?1
IsNull findByAgeIsNull where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull where x.age not null
Like findByFirstnameLike where x.firstname like ?1
NotLike findByFirstnameNotLike where x.firstname not like ?1
StartingWith findByFirstnameStartingWith where x.firstname like ?1 (参数前面加 %)
EndingWith findByFirstnameEndingWith where x.firstname like ?1 (参数后面加 %)
Containing findByFirstnameContaining where x.firstname like ?1 (参数两边加 %)
OrderBy findByAgeOrderByLastnameDesc where x.age = ?1 order by x.lastname desc
Not findByLastnameNot where x.lastname <> ?1
In findByAgeIn(Collection ages) where x.age in ?1
NotIn findByAgeNotIn(Collection age) where x.age not in ?1
True findByActiveTrue() where x.active = true
False findByActiveFalse() where x.active = false
IgnoreCase findByFirstnameIgnoreCase where UPPER(x.firstame) = UPPER(?1)

参考地址:https://github.com/tkaczmarzyk/specification-arg-resolver

你可能感兴趣的:(spring data jpa)