1. 程式人生 > >mybaits 按照欄位排序問題

mybaits 按照欄位排序問題

mybaits 按照欄位排序問題


傳一個map,key表示欄位名, value (true 表示正排序,false 表示反排序):

基礎程式碼

LinkedHashMap<String, Boolean> map = new LinkedHashMap<>();
map.put("user_id",true);
map.put("user_name",false);

1

BaseDao:
List<T> listByPage(@Param("model") T model,@Param("page") PageBean page,
@Param
("map") LinkedHashMap<String,Boolean> map);
xml 裡面如下:
<select id="listByPage" resultMap="BaseResultMap">

        select
        <include refid="Base_Column_List"/>

        from owner_information
        <where>
            <if test="model.userId != null and model.userId != ''"
> and user_id = #{model.userId} </if> <if test="model.userName != null and model.userName != ''"> and user_name= #{model.userName} </if> </where> <foreach collection="map" index="key"
item="value" open=" order by " close=" " separator="," > <if test="value==true"> ${key} desc </if> <if test="value==false"> ${key} asc </if> </foreach> <if test="page != null"> limit #{page.start}, #{page.pageSize} </if> </select>

sql

select * from owner_information order by user_id desc , phone_num asc limit ?, ? 


2

 @Override
    public PageBean<T> page(T model, int currentPage, int pageSize, LinkedHashMap<String, Sorted> orders) {
        int count = getDao().count(model);
        PageBean page = new PageBean(currentPage, pageSize, count);
        StringBuilder sorted = new StringBuilder();

        orders.entrySet().stream().forEach(e -> {
            sorted.append(e.getKey());
            sorted.append(" ");
            sorted.append(e.getValue() == Sorted.DESC ? "desc" : "asc");
            sorted.append(",");
        });

        if (sorted.indexOf(",") != -1) {
            sorted.deleteCharAt(sorted.lastIndexOf(","));
        }
        List<T> list = getDao().listByPage(model, page, sorted.toString());
        page.setRecordList(list);
        return page;
    }
dao

 List<T> listByPage(@Param("model") T model, @Param("page") PageBean page, @Param("sorted") String sorted);
xml

<select id="listByPage" resultMap="BaseResultMap">

        select
        <include refid="Base_Column_List"/>
        from t_business

        <where>

        </where>

        <if test="sorted != null and sorted != '' ">
            order by ${sorted}
        </if>


        <if test="page != null">
            limit #{page.start}, #{page.pageSize}
        </if>


    </select>
                                                                2018.8.6 -9.20 北京 雨