MyBatis分页插件使用实例

业务需求

用SpringBoot + MyBatis 实现分页带条件查询,根据status为0或1,展示相应的order信息

OrderMapper接口

@Repository
public interface OrderMapper {
    /**
     * 根据用户uid,如果有支付状态,则查询条件加上支付状态,查询所有订单信息,根据创建时间由新到老排序
     * @param uid 用户id
     * @param status 订单状态
     * @return
     */
    List<Order> findAllOrdersByUid(Integer uid, Integer status);
}

OrderMapper.xml

<select id="findAllOrdersByUid" resultMap="OrderEntityMap">
    select * from t_order where
    uid=#{uid}
    <if test="status != null">
        and status = #{status}
    if>
    order by order_time desc
select>

IOrderService接口

public interface IOrderService {
    /**
     * 根根据用户uid,如果有支付状态,则查询条件加上支付状态,查询所有订单信息,根据创建时间由新到老排序
     * @param uid 用户id
     * @param status 订单状态
     * @return
     */
    List<Order> getOrdersByUid(Integer uid, Integer status);
    
    /**
     * 分页查询某个用户所有的订单信息
     * @param pageNum 当前页码数,从1开始
     * @param pageSize 每页显示的数据条数
     * @param uid 用户uid
     * @return pageHelper插件内置的分页PageBean对象
     */
     PageInfo<Order> getAllByUidAndPageInfo(Integer pageNum, Integer pageSize, Integer uid, Integer status);
}

OrderServiceImpl实现类

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    
    @Override
    public List<Order> getOrdersByUid(Integer uid, Integer status) {
        List<Order> list = orderMapper.findAllOrdersByUid(uid, status);
        for (Order order : list) {
            //将无关信息置为null
            order.setRecvPhone(null);
            order.setRecvProvince(null);
            order.setRecvCity(null);
            order.setRecvArea(null);
            order.setRecvAddress(null);
            order.setCreatedUser(null);
            order.setCreatedTime(null);
            order.setModifiedUser(null);
            order.setModifiedTime(null);
        }
        return list;
    }
    
    @Override
    public PageInfo<Order> getAllByUidAndPageInfo(Integer pageNum, Integer pageSize, Integer uid, Integer status) {
        // 1. 分页的开始页的分页设置,分页一定要传递这两个参数
        PageHelper.startPage(pageNum, pageSize);

        // 2. 紧跟分页设置后的第一条SQL语句会被分页查询,在SQL语句后自动拼接limit子句
        List<Order> orders = getOrdersByUid(uid, status);

        // 3. pageInfo参数navigatePages表示显示的页码数量
        PageInfo<Order> orderPageInfo = new PageInfo<>(orders);
        return orderPageInfo;
    }
}

OrderController

@RestController
@RequestMapping("/orders")
public class OrderController extends BaseController {
    @Autowired
    private IOrderService orderService;
    
    @RequestMapping("/all_by_page")
    public JSONResult<PageInfo<Order>> allOrdersByPageInfo(HttpSession session,
           @RequestParam(required = false, value = "status") Integer status,
           @RequestParam(required = true, defaultValue = "1", value = "pageNum") Integer pageNum,
           @RequestParam(required = true, defaultValue = "3", value = "pageSize") Integer pageSize) {
        Integer uid = getUidFromSession(session);

        PageInfo<Order> page = orderService.getAllByUidAndPageInfo(pageNum, pageSize, uid, status);
        return new JSONResult<>(OK, page);
	}
}

前端部分代码

静态结构

<div id="column" class="col-md-12 pull-right" align="right">
	<input id="firstPage" type="button" value="首页">
	<input id="pageDown" type="button" value="上一页" class="num-btn" />
	<a id="num" class="num-text">1a>
	<input id="pageUp" class="num-btn" type="button" value="下一页" />
	<input id="lastPage" type="button" value="尾页">
div>

js代码

let numMax = 0;
$(document).ready(function (){
	showOrderList();
});

$("#firstPage").click(function () {
	if ($("#num").html() != 1) {
		$("#num").html(1);
		showOrderList();
	}
});

$("#lastPage").click(function () {
	if ($("#num").html() != numMax) {
		$("#num").html(numMax);
		showOrderList();
	}
});

$("#pageDown").click(function () {
	let tmp = $("#num").html();
	if (tmp > 1) {
		tmp--;
		$("#num").html(tmp);
		showOrderList();
	}
});

$("#pageUp").click(function () {
	let tmp = $("#num").html();
	if (tmp < numMax) {
		tmp++;
		$("#num").html(tmp);
		showOrderList();
	}
});

ajax请求(代码较为臃肿,看个大概就行,根据实际需求来)

function showOrderList() {
	$("#order-list").empty();
	let data = "pageNum=" + $("#num").html();
	let status = $.getUrlParam("status");
	if (status != null) {
		data += "&status=" + status;
	}

	// console.log(location.search.substr(1));
	$.ajax({
		url: "/orders/all_by_page",
		type: "get",
		data: data,
		dataType: "json",
		async: false,
		success: function (json) {
			let list = json.data.list;

			// 只有当numMax没有被赋值的时候,才给numMax赋值
			if (numMax == 0) {
				numMax = json.data.pages;
			}

			for (let i = 0; i < list.length; i++) {

				// 为当前oid查询所有订单项,保存为items
				let items = "";
				$.ajax({
					url: "/orders/items/" + list[i].oid,
					type: "get",
					dataType: "json",
					async: false,
					success: function (json) {
						if (json.state == 200) {
							items = json.data;
						}
					},
					error: function (xhr) {
						alert("展示oid为" + list[i].oid + "的订单项信息时出现未知的异常!" + xhr.message);
					}
				});
				
				// 添加每个订单首部div
				let headDiv = '
'
; headDiv = headDiv.replace(/#{oid}/g, list[i].oid); $("#order-list").append(headDiv); // console.log(headDiv); //添加订单信息的div let orderInfo = '
\n' + '

\n' + '订单号:#{oid},下单时间:#{orderTime}, 收货人:#{name}   ' + '\n' + '

\n'
+ '
'
; orderInfo = orderInfo.replace(/#{oid}/g, list[i].oid); orderInfo = orderInfo.replace(/#{orderTime}/g, list[i].orderTime); orderInfo = orderInfo.replace(/#{name}/g, list[i].recvName); // console.log("orderInfo: "+ orderInfo); $("#order-div-" + list[i].oid).append(orderInfo); //添加表格外层div let tableDiv = '
'
; tableDiv = tableDiv.replace("#{oid}", list[i].oid); $("#order-div-" + list[i].oid).append(tableDiv); //添加表格标签 let tableOid = '
'
; tableOid = tableOid.replace("#{oid}", list[i].oid); $("#table-div-" + list[i].oid).append(tableOid); //添加总金额的div let total = '
\n' + '订单总金额:¥#{totalPrice}\n' + '
'
; total = total.replace(/#{totalPrice}/g, list[i].totalPrice); $("#table-div-" + list[i].oid).append(total); // 添加表格的thead标签 let thead = '\n' + '\n' + '\n' + '商品\n' + '单价\n' + '数量\n' + '小计\n' + '售后\n' + '状态\n' + '操作\n' + '\n' + ''; $("#table-" + list[i].oid).append(thead); // 添加tbody标签 let tbody = ''; tbody = tbody.replace(/#{oid}/g, list[i].oid); $("#table-" + list[i].oid).append(tbody); //为tbody添加tr标签 for (let j = 0; j < items.length; j++) { let item = items[j]; // console.log(item); let tr = '\n' + '\n' + '#{title}\n' + #{price}\n' + '#{num}件\n' + #{total}\n' + '申请售后\n' + '\n' + '
已发货
\n'
+ '\n' + '\n' + '确认收货\n' + ''; tr = tr.replace(/#{image}/g, item.image) .replace(/#{title}/g, item.title) .replace(/#{num}/g, item.num) .replace(/#{price}/g, item.price) .replace(/#{total}/g, item.price * item.num); // console.log(tr); $("#tbody-" + list[i].oid).append(tr); } } }, error: function (xhr) { alert("展示全部订单列表时产生未知的异常!" + xhr.status + " " + xhr.message); } }); }

你可能感兴趣的:(MyBatis,java,spring,boot,spring,数据库,html5)