需求
实体类中有一个 List 类型的属性,对应于 MySQL 表里的 varchar 字段,使用 MyBatis 添加或查询时能互相转换。
解决方案
自定义一个类型处理器:
package com.examples.handler; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ListStringTypeHandler extends BaseTypeHandler> { @Override public void setNonNullParameter(PreparedStatement ps, int i, List parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, String.join(",", parameter)); } @Override public List getNullableResult(ResultSet rs, String columnName) throws SQLException { if (rs.getString(columnName) == null) { return new ArrayList(); } return Arrays.asList(rs.getString(columnName).split(",")); } @Override public List getNullableResult(ResultSet rs, int columnIndex) throws SQLException { if (rs.getString(columnIndex) == null) { return new ArrayList(); } return Arrays.asList(rs.getString(columnIndex).split(",")); } @Override public List getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { if (cs.getString(columnIndex) == null) { return new ArrayList(); } return Arrays.asList(cs.getString(columnIndex).split(",")); } }
示例
Java 实体类
@Data public class Student { private Long id; private String name; private List hobbies; }
数据表的字段
Mapper接口
public interface StudentMapper { void saveStudent(Student student); Student queryStudentById(long id); }
xml文件 需要使用 typeHandler=”com.examples.handler.ListStringTypeHandler”
insert into student (name, hobbies) values (#{name}, #{hobbies,typeHandler=com.examples.handler.ListStringTypeHandler}) select * from student where id = #{id}
测试
public class StudentTest { @Resource private StudentMapper studentMapper; // 添加 @Test void testSaveStudent() { Student student = new Student(); List hobbiesList = new ArrayList(); hobbiesList.add("篮球"); hobbiesList.add("阅读"); hobbiesList.add("写代码"); student.setName("张三"); student.setHobbies(hobbiesList); studentMapper.saveStudent(student); } //查询 @Test void testQueryStudentById() { Student student = studentMapper.queryStudentById(1L); System.out.println(student); } }
添加的结果
查询的结果
到此这篇关于Java中的List和MySQL中的varchar相互转换的解决方案的文章就介绍到这了,更多相关Java List和MySQL varchar相互转换内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!