我现在有这个:
<select id="associations-short-sql" resultMap="associationInfoForListMap">
<![CDATA[
select
a.id as d,
a.name as name,
a.somenum as number
from
associations a
]]>
<if test="id!= null">
where a.id = #{id}
</if>
</select>
但我需要添加过滤功能。因此,如果 uri 查询有参数名称,我想向查询添加类似条件。 id 和 name 都必须是可选的。因此,如果 url 查询中未设置参数,则查询必须是:
select
a.id as d,
a.name as name
a.somenum as number
from
associations a
如果设置了 id 查询必须是:
select
a.id as d,
a.name as name
a.somenum as number
from
associations a
where a.id = #{id}
如果设置了名称,则查询必须为
select
a.id as d,
a.name as name
a.somenum as number
from
associations a
where a.name like '%#{name}%'
如果姓名和号码设置查询必须是:
select
a.id as d,
a.name as name
a.somenum as number
from
associations a
where a.name like '%#{name}%' and number like '%#{number}%'
但是,当设置某些参数时,我必须保持选择语句顺序正确(我的意思是 where
和 and
部分)。这是相当简单的示例,但也可能复杂得多。对于参数name
,我应该检查是否设置了number
,对于参数number,我应该检查是否设置了name
。对于 id,我应该检查名称和号码是否都已设置。如果我有 10 个参数 %!@#!@ 怎么办? :)
是否可以将 where
条件存储在某个临时变量中?保持正确的顺序会容易得多。谢谢。
最佳答案
至少有两种选择可以做到这一点。
动态 SQL
第一个选项是使用 dynamic sql并且适用于许多情况是内置的,不需要额外的配置:
<select id="associations-short-sql" resultMap="associationInfoForListMap">
<![CDATA[
select
a.id as d,
a.name as name,
a.somenum as number
from
associations a
]]>
<where>
<if test="id != null">
a.id = #{id}
</if>
<if test="id == null">
<if test="name != null">
AND a.name = #{name}
</if>
<if test="number != null">
AND a.number = #{number}
</if>
</if>
</where>
</select>
<where>
元素处理 where
时的情况子句为空,不会将其插入到结果 sql 中。如果您仅通过 name
,它还会在开头修剪额外的 AND例如。
脚本
另一个选项是使用 scripting 。在 velocity engine 中编写脚本更具表现力和力量。通常符号更紧凑。 您的示例可能如下所示:
<select id="associations-short-sql" resultMap="associationInfoForListMap">
<![CDATA[
select
a.id as d,
a.name as name,
a.somenum as number
from
associations a
]]>
#where()
#if($_parameter.id)
a.id = @{id}
#else
#if($_parameter.name)
AND a.name = @{name}
#end
#if($_parameter.number)
AND a.number = @{number}
#end
#end
#end
</select>
此外,速度还允许您使用变量、循环等。
关于java - 是否可以在 mybatis "select"中使用临时变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25907404/