我有一个项目需要处理SQL的动态排序人员。
我正在尝试使用包含排序建议的地图列表,通过该列表可以保留排序顺序和排序目标
Java代码: 排序推荐部分:
List<Map<String, String>> sort = new ArrayList<>();
// the key is the field of table which i want to sort
// and the value here is the sort order (asc/desc)
Map<String, String> map1 = new HashMap<>();
map1.put("publish_time", "desc");
sort.add(map1);
Map<String, String> map2 = new HashMap<>();
map2.put("id", "asc");
sort.add(map2);
映射器部分
List<Doc> selectByQuery(DocParam param, Paging paging, List<Map<String, String>> sort);
XML代码: 首先尝试:
select * from doc
where
1 = 1
<if test="sort != null and sort.size() > 0">
order by
<trim suffixOverrides=",">
<foreach collection="sort" item="item" >
<foreach collection="item" index="key" item="value" separator=",">
#{key} #{value}
</foreach>
</foreach>
</trim>
</if>
第二次尝试:
<if test="sort != null and sort.size() > 0">
order by
<trim suffixOverrides=",">
<foreach collection="sort" item="item" >
<foreach collection="item.keys" item="key" open=" " close=" " separator=" " >
<![CDATA[ ${key} #{item[${key}]} ]]>
</foreach>
</foreach>
</trim>
</if>
我想由mybatis构建的最终SQL类似于:
select * from doc
where 1 = 1
order by
publish_time desc,
id asc
,但出现以下错误消息: 第一次尝试:
org.springframework.jdbc.UncategorizedSQLException:
### Error querying database. Cause: java.sql.SQLException: sql injection violation, syntax error: syntax error, error in :'rder by
? ?', expect QUES, actual QUES pos 381, line 31, column 10, token QUES :
select * from doc
where 1 = 1
order by
? ? ,
? ?
第二次尝试:
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'item' not found. Available parameters are [param, paging, sort, param3, param1, param2]
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:77)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446)
at com.sun.proxy.$Proxy96.selectList(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:230)
at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:139)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:76)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
答案 0 :(得分:0)
${}
。请参阅FAQ。separator
是在每个项目之间输出,因此您需要为separator=","
都指定<foreach />
,并且不需要<trim />
。 / li>
HashMap
不保留输入顺序,因此应改用LinkedHashMap
。order by
<foreach collection="sort" item="item" separator=",">
<foreach collection="item" index="key" item="value"
separator=",">
${key} ${value}
</foreach>
</foreach>
答案 1 :(得分:0)
如果您的密钥是动态的,并且是从列表进行迭代的,则可以使用#{dataMap。$ {key}}