实体类接收List<String>
到数据库String
概要
上传图片时需要多张,但最终存入一个字段中。如何快捷的全局处理?而不是手动处理呢?
解决思路和办法
数据接收:
通常我们用List<String>
接收参数,入库时调用一个方法,list2string
数据回显:
从数据库中查询的字符串,如何自动的转成List
实现方式
1.定义一个处理器
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* List<String> 的类型转换器实现类,对应数据库的 varchar 类型
*/
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class StringListJSONTypeHandler implements TypeHandler<List<String>> {
@Override
public void setParameter(PreparedStatement ps, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
ps.setString(i, JSON.toJSONString(strings));
}
@Override
public List<String> getResult(ResultSet rs, String columnName) throws SQLException {
String value = rs.getString(columnName);
return getResult(value);
}
@Override
public List<String> getResult(ResultSet rs, int columnIndex) throws SQLException {
String value = rs.getString(columnIndex);
return getResult(value);
}
@Override
public List<String> getResult(CallableStatement cs, int columnIndex) throws SQLException {
String value = cs.getString(columnIndex);
return getResult(value);
}
private List<String> getResult(String value) {
if (value == null) {
return null;
}
return JSON.parseArray(value, String.class);
}
}
2.在实体类中相应位置添加配置
@Tablename注解中配置属性:autoResultMap = true
用于将字符串转成List
@TableField注解中配置属性:typeHandler = StringListJSONTypeHandler.class
注意StringListJSONTypeHandler
是上面的转换类,用于将List<String>
转成String
。
@TableName(value = "my_images", autoResultMap = true)
@Data
public class Images extends BaseDO {
@TableField(typeHandler = StringListJSONTypeHandler.class)
private List<String> urls;
}