Mybatis自定义类型转换器
需求:有一个类User3,属性favorites为集合类型,将其保存到数据库以字符串形式[xxx,xxxx,xx..]保存。
一、创建User3
public class User3 {
private String username;
private List<String> favorites;
二、配置User3Mapper.xml
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.rong.mapping.User3Mapper">
<insert id="addUser3" parameterType="org.rong.bean.User3">
INSERT INTO user3 SET username=#{username},favorites=#{favorites,typeHandler=org.rong.ListTypeHandler}
</insert>
</mapper>
三、配置代理接口
public interface User3Mapper {
int addUser3(User3 user3);
}
四、注册配置文件
<mappers>
<mapper resource="org/rong/mapping/User3Mapper.xml"/>
</mappers>
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class ListTypeHandler implements TypeHandler<List<String >> {
public void setParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
StringBuffer sb = new StringBuffer();
sb.append("[");
for (int i1 = 0; i1 < strings.size(); i1++) {
sb.append(strings.get(i1));
if (i1 != strings.size()-1){
sb.append(",");
}
}
sb.append("]");
preparedStatement.setString(i,sb.toString());
}
六、测试
public class Main {
public static void main(String[] args) throws IOException {
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getInstance();
SqlSession sqlSession = sqlSessionFactory.openSession();
User3Mapper user3Mapper = sqlSession.getMapper(User3Mapper.class);
User3 user3 = new User3();
user3.setUsername("许文强");
List<String> favorites = new ArrayList<String>();
favorites.add("上海");
favorites.add("打乒乓球");
user3.setFavorites(favorites);
user3Mapper.addUser3(user3);
sqlSession.commit();
sqlSession.close();
}
}