Mybatis自定义类型转换器
需求:有一个类User3,属性favorites为集合类型,将其保存到数据库以字符串形式[xxx,xxxx,xx..]保存。
一、创建User3
public class User3 {
private String username;
private List favorites;
二、配置User3Mapper.xml
INSERT INTO user3 SET username=#{username},favorites=#{favorites,typeHandler=org.rong.ListTypeHandler}
三、配置代理接口
public interface User3Mapper {
int addUser3(User3 user3);
}
四、注册配置文件
五、编写类型转换器
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class ListTypeHandler implements TypeHandler> {
public void setParameter(PreparedStatement preparedStatement, int i, List 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 favorites = new ArrayList();
favorites.add(“上海”);
favorites.add(“打乒乓球”);
user3.setFavorites(favorites);
user3Mapper.addUser3(user3);
sqlSession.commit();
sqlSession.close();
}
}
————————————————
版权声明:本文为CSDN博主「xiaozhuozi888」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xiaozhuozi888/article/details/78875923