Mybatis-Error设置null参数

时间:2011-12-10 09:18:18

标签: mybatis

我使用了mybatis-spring-1.0.3-SNAPSHOT mybatis-3.0.6 spring3.0.6。我试图从这样的表中删除记录:

        <delete id="deleteNote" parameterType="hashMap">
    DELETE FROM BBSCS_NOTE 
    <where>
        <if test="ids !=null and ids.length > 0">
            <foreach collection="ids" item="id" open="(" close=")" separator=",">
                ID IN #{id}
            </foreach>
        </if>
        <if test="toID != null and toID != ''">AND TOID = #{toID}</if>
        <if test="fromID != null and fromID != ''">AND FROMID = #{fromID}</if>
        <if test="noteType != -1">AND NOTETYPE = #{noteType}</if>
    </where>         
</delete>

如您所见,它是一个动态的sql。像这样的java测试代码:

Map map = new HashMap();
String ids[] = {"1","2","3"};
map.put("ids", ids);
noteService.del(map);

当我执行java测试代码时,有一些例外:

   org.springframework.jdbc.UncategorizedSQLException: Error setting null parameter.  Most JDBC drivers require that the JdbcType must be specified for all nullable parameters. Cause: java.sql.SQLException: Invalid column type
; uncategorized SQLException for SQL []; SQL state [null]; error code [17004]; Invalid column type; nested exception is java.sql.SQLException: Invalid column type

为什么?你能给我一些解决这个问题的建议吗?谢谢。

2 个答案:

答案 0 :(得分:19)

好的,我看到了一些问题。首先,将空参数设置为Prepared Statement或Callable语句时,MyBatis需要知道jdbc类型。 像这样,

#{myNullParamenter, jdbcType=VARCHAR}

您还错误地生成了'in子句。您需要使用foreach标记仅生成值列表。将“ID IN”部分移出foreach标记。

<if test="ids !=null and ids.length > 0">
    ID IN
    <foreach collection="ids" item="id" open="(" close=")" separator=",">
        #{id}
    </foreach>
</if>

我还建议不要使用HashMaps。新的Mapper类要好得多。

答案 1 :(得分:13)

问题在于,从3.0.x版本开始,null参数的默认JDBC类型为Types.OTHER,某些JDBC驱动程序(如 Oracle 10g )不支持这种类型。

Here一篇解释此问题的帖子。

我发现的解决方案非常简单,我在配置文件中将jdbcTypeForNull设置为NULL

<configuration>
    <properties resource="mybatis-config.properties" />
    <settings>
        <setting name="jdbcTypeForNull" value="NULL" />
    </settings>

    <environments default="development">
    ....
    </environments>

    <mappers>
    ....
   </mappers>
</configuration>