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 北京 雨

猜你喜欢

转载自blog.csdn.net/qq_25004825/article/details/81448831