1. 程式人生 > >動態sql實現分頁查詢

動態sql實現分頁查詢

類對象 span ecp IT clas listitem 結果 創建 sku

1.創建實體類對象需要查詢的條件com.rl.ecps.model.QueryCondition

  private Long brandId;
  private Short auditStatus;
  private Short showStatus;
  private String itemName;
  private Integer pageNo;
  private Integer startNum;
  private Integer endNum;

2.查詢語句

查詢條數:

<select id="selectItemByConditionCount" parameterType="com.rl.ecps.model.QueryCondition" resultType="int">
select count(*) from eb_item t
<where>
<if test="brandId != null">
t.brand_id = #{brandId}
</if>
<if test="auditStatus != null">
and t.audit_status = #{auditStatus}
</if>
<if test="showStatus != null">
and t.show_status = #{showStatus}
</if>
<if test="itemName != null and itemName != ‘‘">
and t.item_name like ‘%${itemName}%‘
</if>
</where>
</select>

分頁查詢:

<select id="selectItemByCondition" parameterType="com.rl.ecps.model.QueryCondition" resultMap="BaseResultMap">
select *
from (select rownum rw, a.*
from (
select * from eb_item t
<where>
<if test="brandId != null">
t.brand_id = #{brandId}
</if>
<if test="auditStatus != null">
and t.audit_status = #{auditStatus}
</if>
<if test="showStatus != null">
and t.show_status = #{showStatus}
</if>
<if test="itemName != null and itemName != ‘‘">
and t.item_name like ‘%${itemName}%‘
</if>
</where>
order by t.item_id desc
<![CDATA[
) a
where rownum < #{endNum}) b
where b.rw > #{startNum}
]]>
</select>

3.分頁實體類

public class Page {

/**
* 當前頁碼 (已知)
*/
private int pageNo = 1;

/**
* 每頁記錄數(已知)
*/
private int pageSize = 5;

/**
* 指定的查詢條件下的總記錄數
*/
private int totalCount = 0;

/**
* 指定的查詢條件下的總頁數
*/
private int totalPage = 1;

/**
* 查詢的開始行號
*/
private int startNum = 0;

/**
* 查詢的結束行號
*/
private int endNum = 0;

/**
* 查詢的結果集
*/
private List<?> list;

4.service與control

service實現:

public Page selectItemByQC(QueryCondition qc) {
//查詢當前的查詢條件下的總記錄數
int totalCount = itemDao.selectItemByConditionCount(qc);
//創建page對象
Page page = new Page();
page.setPageNo(qc.getPageNo());
page.setTotalCount(totalCount);
//計算startNum和endNum
Integer startNum = page.getStartNum();
Integer endNum = page.getEndNum();
//把值設置給sql的查詢對象
qc.setStartNum(startNum);
qc.setEndNum(endNum);
//查詢結果集
List<EbItem> itemList = itemDao.selectItemByCondition(qc);
page.setList(itemList);
return page;
}

public void saveItem(EbItem item, EbItemClob itemClob,
List<EbParaValue> paraList, List<EbSku> skuList) {
itemDao.saveItem(item);
itemClobDao.saveItemClob(itemClob, item.getItemId());
paraDao.saveParaValue(paraList, item.getItemId());
skuDao.saveSku(skuList, item.getItemId());
}

controller類:

@RequestMapping("/listItem.do")
public String listItem(QueryCondition qc, Model model){
List<EbBrand> bList = brandService.selectBrandAll();
model.addAttribute("bList", bList);
if(qc.getPageNo() == null){
qc.setPageNo(1);
}
Page page = itemService.selectItemByQC(qc);
model.addAttribute("page", page);
//把qc寫回去,目的是回顯
model.addAttribute("qc", qc);
return "item/list";
}

動態sql實現分頁查詢