spring jpa 动态查询

在业务中需要动态查询,多方查询之后感觉还可以.简单的动态查询

代码如下

 override fun findAll(map: Map, pageable: Pageable): Page {
        var mySpec: Specification = Specification { root: Root, criteriaQuery, criteriaBuilder ->
            var exp1: Path? = root.get("no")
            var exp2: Path? = root.get("createBy")
            var exp3: Path? = root.get("status")
            var type = map["type"]
            var status = map["status"]
            var predicate: Predicate = criteriaBuilder.conjunction()
            if ((status as String).isNotBlank()) {
                predicate.expressions.add(criteriaBuilder.equal(exp3, status))
            }
            if ((type as String).isNotBlank()) {
                predicate.expressions.add(criteriaBuilder.or(criteriaBuilder.like(exp1, "%$type%"),
                        criteriaBuilder.like(exp2, "%$type%")))
            }
            predicate
        }
        return snRepository.findAll(mySpec, pageable)
    }

mysql 的find_in_set也是很好用
在使用find_in_set的时候 jpa好像是并不支持这样搜索。
所以决定用原生sql,此时产生一个问题。之前传一个pageable参数进去后,jpa就会自动分页排序,最后在stackoverflow上找到一个解决方法
原文地址

 @Query(value = "select * from user_invest  where find_in_set(?1,investField)>0 and institution like %?2% ORDER BY ?#{#pageable}",
            countQuery = "select count(*) from user_invest  where find_in_set(?1,investField)>0 and institution like %?2%  ",
            nativeQuery = true)
    fun  findByFieldAndKeyword(filed: Int, keyword: String, pageable: Pageable): Page

记录一下,日后参考

你可能感兴趣的:(spring jpa 动态查询)