如何在 MyBatis 中将方法应用于参数
在阅读了 Mapper XMLs 后,我不禁想知道人们会如何去关于对参数应用一些常见的转换。例如...
<select id="selectPerson" parameterType="String" resultType="hashmap">
<!-- #{name} should always be upper case and have a trailing % -->
SELECT * FROM PERSON WHERE FIRST_NAME like #{name}
</select>
- 使用
upper
或concat
或'||'
或'+'
等 SQL 函数进行转换会降低性能在 DB2 中, - 我总是可以包装映射器或在服务层中公开详细信息,但这看起来很混乱
我想要的是能够做类似的事情...
<select id="selectPerson" parameterType="String" resultType="hashmap">
<!-- #{name} should always be upper case and have a trailing % -->
SELECT * FROM PERSON WHERE FIRST_NAME like #{name.upperCase() + '%'}
</select>
这样的事情可能吗?或者第二个最佳解决方案是什么?
更新:看来 MyBatis 使用 OGNL 进行某些表达式求值。例如,if
和 ${}
表达式使用 OGNL,但 #{}
似乎不会,除非有某种方法可以欺骗它。< /em>
After reading about Mapper XMLs I can't help to wonder how one might go about appling some common transforms to a parameter. For example...
<select id="selectPerson" parameterType="String" resultType="hashmap">
<!-- #{name} should always be upper case and have a trailing % -->
SELECT * FROM PERSON WHERE FIRST_NAME like #{name}
</select>
After reading this and this I can make some observations.
- Using SQL functions such as
upper
orconcat
or'||'
or'+'
to do transforms kills performance in DB2 - I could always wrap the the mapper or expose the details in the service layer but that seems messy
What I want is to be able to do something like...
<select id="selectPerson" parameterType="String" resultType="hashmap">
<!-- #{name} should always be upper case and have a trailing % -->
SELECT * FROM PERSON WHERE FIRST_NAME like #{name.upperCase() + '%'}
</select>
Is something like this possible or what is the second best solution?
Update: it appears that MyBatis uses OGNL for some expression evaluation. For example, if
and ${}
expressions use OGNL but #{}
does NOT appear to unless there is some way to trick it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Bind
MyBatis 允许使用
。Bind 在当前语句的范围内创建一个新变量。绑定值的 OGNL 语句可以使用传入的 _parameter 对象来计算新的绑定值,然后 MyBatis 可以使用该值来构造准备好的语句。
示例
使用绑定的示例:
来源
Bind
MyBatis allows for creating values from method and properties in the context using
<bind/>
.Bind creates a new variable in the scope of the current statement. The OGNL statement that binds the value can use the passed in
_parameter
object to compute a new bound value that can then used by MyBatis to construct the prepared statement.Example
Your example using bind:
Source
我也遇到了同样的问题。但我没有找到任何解决方案。因此,我必须预处理调用函数中的
#{name}
参数。I ran through the same problem too. But I didn't find any solution for this. So I had to preprocess the
#{name}
parameter from the calling function.