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">1</a>
	<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 = '<div id="order-div-#{oid}" class="panel panel-default"></div>';
				headDiv = headDiv.replace(/#{oid}/g, list[i].oid);
				$("#order-list").append(headDiv);
				// console.log(headDiv);

				//添加订单信息的div
				let orderInfo = '<div class="panel-heading">\n' +
						'<p class="panel-title">\n' +
						'订单号:#{oid},下单时间:#{orderTime}, 收货人:#{name}&nbsp;&nbsp;&nbsp;' +
						'<input type="button" οnclick="delOrder(#{oid})" class="cart-del btn btn-default btn-xs" value="删除" />\n' +
						'</p>\n' +
						'</div>';
				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 = '<div id="table-div-#{oid}" class="panel-body"></div>';
				tableDiv = tableDiv.replace("#{oid}", list[i].oid);
				$("#order-div-" + list[i].oid).append(tableDiv);

				//添加表格标签
				let tableOid = '<table id="table-#{oid}" class="orders-table" width="100%"></table>';
				tableOid = tableOid.replace("#{oid}", list[i].oid);
				$("#table-div-" + list[i].oid).append(tableOid);

				//添加总金额的div
				let total = '<div>\n' +
						'<span class="pull-right">订单总金额:¥#{totalPrice}</span>\n' +
						'</div>';
				total = total.replace(/#{totalPrice}/g, list[i].totalPrice);
				$("#table-div-" + list[i].oid).append(total);


				// 添加表格的thead标签
				let thead = '<thead>\n' +
						'<tr>\n' +
						'<th width="15%"></th>\n' +
						'<th width="30%">商品</th>\n' +
						'<th width="8%">单价</th>\n' +
						'<th width="8%">数量</th>\n' +
						'<th width="9%">小计</th>\n' +
						'<th width="10%">售后</th>\n' +
						'<th width="10%">状态</th>\n' +
						'<th width="10%">操作</th>\n' +
						'</tr>\n' +
						'</thead>';
				$("#table-" + list[i].oid).append(thead);

				// 添加tbody标签
				let tbody = '<tbody id="tbody-#{oid}" class="orders-body"></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 = '<tr>\n' +
							'<td><img src="..#{image}collect.png" class="img-responsive" /></td>\n' +
							'<td>#{title}</td>\n' +
							'<td>¥<span>#{price}</span></td>\n' +
							'<td>#{num}件</td>\n' +
							'<td>¥<span>#{total}</span></td>\n' +
							'<td><a href="#">申请售后</a></td>\n' +
							'<td>\n' +
							'<div>已发货</div>\n' +
							'<div><a href="orderInfo.html">订单详情</a></div>\n' +
							'</td>\n' +
							'<td><a href="#" class="btn btn-default btn-xs">确认收货</a></td>\n' +
							'</tr>';
					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);
		}
	});
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis使用分页插件可以方便地实现分页查询功能。下面是一个示例的 MyBatis 分页插件配置类: ```java import com.github.pagehelper.PageHelper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Properties; @Configuration public class MybatisPageConfig { @Bean public PageHelper pageHelper() { PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); // 设置数据库方言,用于解析分页的 SQL 语句 properties.setProperty("helperDialect", "mysql"); // 设置是否将参数转换为查询字符串中的 limit 和 offset properties.setProperty("offsetAsPageNum", "true"); // 设置是否进行 count 查询 properties.setProperty("rowBoundsWithCount", "true"); // 设置是否分页合理化,即当页码小于 1 或大于总页数时,是否返回第一页或最后一页的数据 properties.setProperty("reasonable", "true"); // 配置属性 pageHelper.setProperties(properties); return pageHelper; } } ``` 在该配置类中,通过 `PageHelper` 类创建一个分页插件实例,并配置了几个重要的属性。`helperDialect` 属性指定了数据库方言,这里以 MySQL 为例;`offsetAsPageNum` 属性设置为 `true`,将参数转换为查询字符串中的 `limit` 和 `offset`;`rowBoundsWithCount` 属性设置为 `true`,表示会进行 count 查询来获取总记录数;`reasonable` 属性设置为 `true`,用于处理不合理的分页参数。 以上是一个简单的 MyBatis 分页插件配置类的示例,你可以根据自己的业务需求进行进一步的配置和定制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值