SoFunction
Updated on 2025-04-05

Summary of the problem of implementing dynamic ascending and descending order in mybatis

question

Recently, there is a requirement that the front-end tells the back-end to sort by a certain field. Here we mainly focus on the xml implementation of mybatis, and other Spring integrations are ignored.

mapper xml implementation

<if test="sortField != null and sortField != ''">
    ORDER BY
    <choose>
        <when test="sortField == 'perCapitaEffectivePoints'">
            per_capita_effective_points ${sortOrder}
        </when>
        <when test="sortField == 'perCapitaCumulativePoints'">
            per_capita_cumulative_points ${sortOrder}
        </when>
        <otherwise>
            dept_name
        </otherwise>
    </choose>
</if>

Note that the use here is$Instead of using#, if used#The syntax mybatis spliced ​​out Order by clause does not conform to SQL syntax. Only use$Syntax references variables. Here we also need to do some anti-injection processing in the java code. Similar to the following:

String validatedSortOrder = "DESC".equalsIgnoreCase(sortOrder) ? "DESC" : "ASC";

Then use the validatedSortOrder variable to pass the data to mybatis.

This is the end of this article about realizing dynamic ascending and descending order in mybatis. For more related ascending and descending content in mybatis, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!