简体   繁体   English

使用MyBatis动态选择SQL语句

[英]Dynamic Select SQL statements with MyBatis

I would like to have dynamic sql statements using mybatis in an Oracle 12g database where I can utilize a hash map to add conditionals something like the following: 我想在Oracle 12g数据库中使用mybatis使用动态sql语句,在该数据库中我可以利用哈希图添加条件,如下所示:

<select id="getUsers" resultType="hashmap" parameterType="hashmap"> 
  select * 
  from users 
  <where> 
  <iterate var="i=0" increment> 
    ${columni} like #{valuei} 
  </iterate> 
  </where> 
</select> 

Is there a way for me to accomplish something like that? 我有办法完成类似的事情吗?

From documentation : 文档

String Substitution 字符串替换

By default, using the #{} syntax will cause MyBatis to generate PreparedStatement properties and set the values safely against the PreparedStatement parameters (eg ? ). 默认情况下,使用#{}语法将使MyBatis生成PreparedStatement属性,并根据PreparedStatement参数(例如? )安全地设置值。 While this is safer, faster and almost always preferred, sometimes you just want to directly inject a string unmodified into the SQL Statement. 尽管这是更安全,更快且几乎总是首选的,但有时您只想直接将未经修改的字符串插入SQL语句。 For example, for ORDER BY , you might use something like this: 例如,对于ORDER BY ,您可以使用如下代码:

ORDER BY ${columnName}

Here MyBatis won't modify or escape the string. 在这里MyBatis不会修改或转义字符串。

This allows you to eg pass column names as parameters to query etc. 这允许您例如将列名作为参数传递给查询等。

Remember to always sanitize data that you are directly pasting to SQL. 请记住, 始终清除直接粘贴到SQL的数据。


If you need to generate multiple conditions for WHERE clause, use <where> tag with <foreach> inside. 如果您需要为WHERE子句生成多个条件,请<where>内部的<foreach>使用<where>标记。 Note that <foreach> has advanced attributes that allow to specify separator, opening/ending string etc. Combined with ${} notation I've mentioned before this allows construction of dynamic WHERE clause. 请注意, <foreach>具有允许指定分隔符,打开/结束字符串等的高级属性。与${}符号结合${}我之前已经提到过),可以构造动态WHERE子句。 For an example, see this answer . 有关示例,请参见此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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