springDataJpa实现普通模糊查询
1.需求
2.页面代码
<input type="text" id="id_keywords" class="form-control" placeholder="请输入区域、小区名">
<div class="col-md-2 col-sm-2 col-xs-2 pt0">
<span class="btn1" id="btn_keywords_search">
<i class="fa fa-search" aria-hidden="true"></i>搜索</span>
</div>
3.js代码
$('#btn_keywords_search').click(function() {
var query = $('#id_keywords').val();
searchByCondition(query);
})
function searchByCondition(query){
$.ajax({
type : 'post',
url : 'searchCommon',
cache : false, // 禁用缓存
data : {
query: query,
page:0
},
success : function(data) {
console.log(data);
var list=data.contents.data;
var str="";
var tal="";
tal+='<div class="fl" id="btn-tal"><b>'+data.contents.total+'</b>套</div>'
for(var i=0;i<list.length;i++){
var item = list[i];
str+='<li class="clearfix" roomid="100241047" lng="114.260571" lat="22.725271" title="东方明珠城 龙岗龙城广场站家私家电全齐2房出租">'
str+='<a class="big-alink clearfix" href=" \"/room/ \"+item.roomsn+\".html\" " target="_blank"> '+'<p class="hs-photo fl">'+'<img src="/upload/viewImg2/'+item.smallImg+' width="135" height="102" class="fl"></p>'
str+='<div class="hs-info fl">'+'<p class="hs-info-name">'+item.roomName+'</p>'+'<p>'+item.cityName+item.areaName+'</p>'
+'<p>'+item.tips+'</p>'+'<p class="hs-info-price">'+'¥'+item.rental+'元/月</p></div></a><li>'
}
$("#btn-tal").html(tal);
$("#roomList").html(str);
}
});
}
4.控制层代码
@PostMapping("searchCommon")
@ResponseBody
public Map<String, Object> searchCommon(String query, Integer page) {
Integer limit = Consts.PAGE_SIZE;
TblRooms entity = new TblRooms();
entity.setKeyword(query);
PageRequest pageRequest = PageRequest.of(page, limit, Direction.DESC, "id");
Map<String, Object> datas;
datas = tblRoomsService.findAll(entity, pageRequest);
Map<String, Object> map = new HashMap<String, Object>();
map.put("contents", datas);
return map;
}
5.业务层主要代码
if (StringUtils.isNotBlank(entity.getKeyword())) {
list.add(cb.or(cb.like(root.get("cityName").as(String.class), "%" + entity.getKeyword() + "%"),
cb.like(root.get("areaName").as(String.class), "%" + entity.getKeyword() + "%"),
cb.like(root.get("subways").as(String.class), "%" + entity.getKeyword() + "%"),
cb.like(root.get("roomName").as(String.class), "%" + entity.getKeyword() + "%")
));
}