本文共 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)); Pagelist = clothesDao.findByKeyword("衣服", pageable); System.out.println(list.getContent().size()); for(Clothes clothes : list.getContent()){ System.out.println(clothes); } }}
转载地址:http://kfern.baihongyu.com/