博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot-JPA自定义SQL(分页)语句
阅读量:3924 次
发布时间:2019-05-23

本文共 2077 字,大约阅读时间需要 6 分钟。

package com.example.clothingmanager.dao;import com.example.clothingmanager.bean.Clothes;import org.springframework.data.domain.Page;import org.springframework.data.domain.Pageable;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.Query;import java.util.List;/** * @author Huangyt * @version 1.0 * @date 2020/5/7 16:45 */public interface ClothesDao extends JpaRepository
{
//第一种写法 @Query(value = "select * from tb_clothes where cname like CONCAT('%', :keyword, '%')", nativeQuery = true, countQuery = "select count(1) from tb_clothes") public Page
findByKeyword(String keyword, Pageable pageable); //第二种写法 //@Query(value = "select * from tb_clothes where cname like CONCAT('%', ?1, '%')", nativeQuery = true, countQuery = "select count(1) from tb_clothes") //public Page
findByKeyword(String keyword, Pageable pageable);}}

第一种写法确保无误,不会报错。

但是第二种写法虽然这里不报错,但是在其它地方可能会报错,所以还是统一采取第一种写法好

采取第二种写法可能会无法读取参数:

Could not locate ordinal parameter [1], expecting one of []

调用

package com.example.clothingmanager;import com.example.clothingmanager.bean.Clothes;import com.example.clothingmanager.dao.ClothesDao;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.data.domain.Page;import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Pageable;import org.springframework.data.domain.Sort;import java.util.List;@SpringBootTestclass ClothingmanagerApplicationTests {    @Autowired    ClothesDao clothesDao;    @Test    void contextLoads() {        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "citem");        Pageable pageable = PageRequest.of(1, 5, Sort.by(order));        Page
list = clothesDao.findByKeyword("衣服", pageable); System.out.println(list.getContent().size()); for(Clothes clothes : list.getContent()){ System.out.println(clothes); } }}

转载地址:http://kfern.baihongyu.com/

你可能感兴趣的文章
go语言机器学习分类之逻辑回归与k-NN
查看>>
go语言机器学习--集群技术
查看>>
go语言学习时间序列和异常检测
查看>>
go语言神经网络和深度学习
查看>>
GO语言goWeb学习笔记之Http协议与goWeb简洁
查看>>
GoWeb的数据库操作
查看>>
Linux实操--实用指令Day3
查看>>
Mysql 事务处理
查看>>
Linux实操--实用指令Day4
查看>>
Linux实操--实用指令Day3
查看>>
spring+springboot认识
查看>>
Leetcode 136. 只出现一次的数字
查看>>
Leetcode 11. 盛最多水的容器
查看>>
Leetcode 121. 买卖股票的最佳时机
查看>>
Leetcode 123. 买卖股票的最佳时机 III
查看>>
Leetcode 24. 两两交换链表中的节点
查看>>
Leetcode 100. 相同的树
查看>>
Leetcode 257. 二叉树的所有路径
查看>>
Leetcode 4. 寻找两个正序数组的中位数
查看>>
Leetcode 101. 对称二叉树
查看>>