iBatis 动态SQL别名查询结果为Null问题
在项目中使用了iBatis,使用xml方便的维护SQL,清晰明了,偶然发现动态拼接的SQL语句在数据中执行很好的返回结果,而到了程序中总是有字段返回null值,跟在数据库中执行的结果不一致
例如
<select id="getUser" parameterClass="SearchModel" resultClass="UserTO">
select id,name
<dynamic>
<isNotNull property="birthday" prepend=",">
time AS birthday
</isNotNull>
</dynamic>
from user
</select>
这个简单查询中,“birthday”这个字段是在传入参数birthday不为null的情况才会返回,有时候即使数据库中time字段有值也会返回null,这个是因为iBatis机制的问题,这是因为只定义了birthday字段不为null时返回的别名(值),而另外的情况未为iBatis设置返回规则,默认的iBatis就会都返回null
解决方法
iBatis中
- isNotNull
- isNull
- isNotEmpty
- isEmpty
- isNotEqual
- isEqual
这种动态判断关键字最好是成对出现,将所有情况规则都写出来,避免iBatis使用默认规则导致的动态SQL别名字段返回为Null问题
<select id="getUser" parameterClass="SearchModel" resultClass="UserTO">
select id,name
<dynamic>
<isNotNull property="birthday" prepend=",">
time AS birthday
</isNotNull>
<isNull property="birthday" prepend=",">
null AS birthday
</isNull>
</dynamic>
from user
</select>
注意: iBatis中的动态拼接SELECT 后面列时,会出现 “索引超出了数组界限”的错误,需要将动态拼接的情况写完整,类似上述情况