簡體   English   中英

嘗試插入空值時,spring出現mybatis錯誤

[英]Error in mybatis with spring when try to insert nulls

我正在嘗試執行此插入操作:

@Insert("" +
            "insert into EXTRANET.EX_ENTIDAD (ENT_REFNUM, ENT_TIPO, REG_PUB_ID, OFIC_REG_ID, AREA_REG_ID, " +
            "COD_LIBRO, NUM_PARTIDA, ANO_TITU, NUM_TITU, ENT_TRIGGER, TMSTMP_CREA, PRIORIDAD) " +
            " values (EXTRANET.EX_ENTIDAD_SEQ.nextval, #{entTipo}, " +
            "#{regPubId}, #{oficRegId}, #{areaRegId}, #{codLibro}, #{numPartida}, #{anoTitu}, " +
            " #{numTitu}, 'SYNC', SYSDATE, #{prioridad})")
    public int insertEntidades(Map map);

但是,如果某些#{param}為NULL,則會報錯:

由以下原因引起:org.apache.ibatis.type.TypeException:使用JdbcType NULL為參數#1設置null時出錯。 嘗試為此參數設置其他JdbcType或其他jdbcTypeForNull

我正在搜索一些解決方案,並讀到必須配置屬性:jdbcTypeForNull

然后在Spring中更新配置:

@Bean
public SqlSessionFactoryBean sqlSessionFactory() throws Exception,Throwable  {
    SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setDataSource(getDataSource());
    //sessionFactory.setConfigLocation( new ClassPathResource("gob.pe.sunarp.extranet.config.config.xml"));
    sessionFactory.setTypeAliasesPackage("gob.pe.sunarp.extranet.dao.beans");
    final Properties sqlSessionFactoryProperties = new Properties();
    sqlSessionFactoryProperties.put("jdbcTypeForNull", "NULL");
    sessionFactory.setConfigurationProperties(sqlSessionFactoryProperties );

    return sessionFactory;
}

但是錯誤仍然存​​在。

我發現了許多針對xml的解決方案,但僅使用Java接口。
關於此錯誤的一些想法?

根據MyBatis文檔

如果將null作為值傳遞,則JDBC對於所有可為空的列都需要JDBC類型。 您可以通過閱讀PreparedStatement.setNull()方法的JavaDocs自己進行調查。

您是否為參數設置了jdbcType? 例如:

#{property,javaType=int,jdbcType=NUMERIC}

文檔中所述,設置jdbcTypeForNull可能不適用於您的驅動程序。

當沒有為參數提供特定的JDBC類型時,為空值指定JDBC類型。 一些驅動程序需要指定列JDBC類型,但其他驅動程序則可以使用NULL,VARCHAR或OTHER等通用值。

試試這樣的東西

Map<String, Object> map = new HashMap<>();
map.put("entTipo", (Long) null);

insertEntidades(map);

如果您需要全局設置,請嘗試這樣的操作

用Java代碼

sqlSessionFactoryProperties.put("jdbcTypeForNull", JdbcType.DATE);

或在mybatis-config.xml中

<configuration>
    <settings>
        <setting name="jdbcTypeForNull" value="DATE" />             
    </settings>    
</configuration>

這樣,您就可以為任何DATE列插入/更新。

我建議使用mybatis-config.xml解決方案以避免單元測試出現問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM