如何将类型为java.util.Set的数据插入到使用ibatis设置的类型列的sql数据库中?
问题描述:
如何将类型为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.
请帮忙。谢谢 !
答
我想你明确地想要与(旧)ibatis而不是Mybatis一起工作。 所以这里是我引用的documentation。
Mysql SET需要一串以逗号分隔且没有空格的设置值:StringUtils.join(set, ",")
。因此,您必须使用类型处理程序将java Set转换为此字符串:扩展BaseTypeHandler,特别是覆盖setParameter
方法。
然后调用如下:
INSERT INTO USERINFO (ID,CHANGEDFIELDSET)
VALUES(#id#,#changedfieldset,handler=YourCustomTypeHandlerTypeAlias#)
一流的!谢谢 ! 同时我改变了我的Set的getter返回字符串工作正常。但这是真正的解决方案。谢谢哥们 。 – iAmLearning