2017-10-18 154 views
0

如何將類型爲java.util.Set的數據插入到類型爲set(mysql set type)的mysql數據庫列中?如何將類型爲java.util.Set的數據插入到使用ibatis設置的類型列的sql數據庫中?

我的POJO:

public class UserTEO 
{ 
    private Integer id; 
    private Set changedfieldset; 
    //getters and setters 
} 

XML文件:

<sqlMap namespace="user"> 

    <typeAlias alias="USER" type="com.howtodoinjava.ibatis.demo.dto.UserTEO" /> 
    <insert id="addUser" parameterClass="USER"> 
     INSERT INTO USERINFO (ID,CHANGEDFIELDSET) 
     VALUES(#id#,#changedfieldset#); 
    </insert> 
</sqlMap> 

數據庫:

CREATE TABLE USERINFO 
(
    ID INT, 
    CHANGEDFIELDSET SET('') 
); 

例外:

com.ibatis.common.jdbc.exception.NestedSQLException: 
--- The error occurred in user.xml. 
--- The error occurred while applying a parameter map. 
--- Check the user.addUser-InlineParameterMap. 
--- Check the parameter mapping for the 'changedfieldset' property. 

請幫忙。謝謝 !

回答

1

我想你明確地想要與(舊)ibatis而不是Mybatis一起工作。 所以這裏是我引用的documentation

Mysql SET需要一串以逗號分隔且沒有空格的設置值:StringUtils.join(set, ",")。因此,您必須使用類型處理程序將java Set轉換爲此字符串:擴展BaseTypeHandler,特別是覆蓋setParameter方法。

然後調用如下:

INSERT INTO USERINFO (ID,CHANGEDFIELDSET) 
     VALUES(#id#,#changedfieldset,handler=YourCustomTypeHandlerTypeAlias#) 
+0

一流的!謝謝 ! 同時我改變了我的Set的getter返回字符串工作正常。但這是真正的解決方案。謝謝哥們 。 – iAmLearning

相關問題