如何使用 ibatis 将类型为 java.util.Set 的数据插入到我的 sql 数据库中,并设置了类型列?

How to insert data of type java.util.Set into my sql database with column of type set using ibatis?

如何将 java.util.Set 类型的数据插入到 mysql 类型集的数据库列中(mysql 集类型)?

我的 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. 

请帮忙。谢谢!

我猜你明确想要使用(旧的)ibatis 而不是 Mybatis。 所以这是我引用的documentation

Mysql SET 需要一串由逗号分隔且没有空格的设置值:StringUtils.join(set, ",")。因此,您必须使用类型处理程序将 java Set 转换为此字符串:Extend BaseTypeHandler,特别是覆盖 setParameter 方法。

然后调用如下:

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