简体   繁体   中英

Mybatis - Iterate the key/value of a HashMap which belongs to an ArrayList

I've got a project which need to handle dynamic sorting staff for SQL.

I'm trying to use a list of map which contains the sort commends, with which could keep the sort order and sort targets

Java code: Sort commend part:

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);

Mapper part

List<Doc> selectByQuery(DocParam param, Paging paging, List<Map<String, String>> sort);

XML code: first try:

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>

second try:

<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>

the final sql i suppose to build by mybatis is something like:

select * from doc
where 1 = 1
order by
publish_time desc,
id asc

but the following error messages appears: first time trying:

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
? ? ,
? ?

second time trying:

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)

如果您的密钥是从列表中迭代的动态密钥,您可以使用 #{dataMap.${key}}

  • Those values must be output as literals, so you must use ${} . See the FAQ .
  • separator is output between each item, so you need to specify separator="," for both <foreach /> and don't need <trim /> .
  • As HashMap does not keep the entry order, you should use LinkedHashMap instead.
order by
<foreach collection="sort" item="item" separator=",">
  <foreach collection="item" index="key" item="value"
    separator=",">
    ${key} ${value}
  </foreach>
</foreach>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM