Spring boot實現模糊查詢

使用註解方式

記得查詢時要加通配符來表示個數等信息!
參考博文,SQL模糊查詢語句


SearchController.java

package cn.shop.controller;

import cn.shop.entity.Shoe;
import cn.shop.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping(value = "search")
public class SearchController {

    private Logger logger = LoggerFactory.getLogger(SearchController.class);

    @Autowired
    private ProductService productService;

    @RequestMapping(value = "")
    @ResponseBody
    public List<Shoe> showSearch(@RequestParam(value = "key") String key ,
                             Model model){
        logger.info("key:" + key);
        List<Shoe> list = productService.searchShoes(key);
        logger.info("查詢結果個數:" + list.size());
        return list;
    }

}

ProductService.java

package cn.shop.service;

import cn.shop.entity.Shoe;
import cn.shop.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    public List<Shoe> searchShoes(String key){
        //記得加 %  %
        return productRepository.findAllByNameLike("%" + key + "%");
    }
}

ProductRepository.java

package cn.shop.repository;

import cn.shop.entity.Shoe;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface ProductRepository extends JpaRepository<Shoe,Integer>{

    public List<Shoe> findAllByNameLike(String key);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章