今天遇到一个问题,在数据库层存储的是
“user_floorvarchar(50) NOT NULL DEFAULT '' COMMENT '负责楼层',
但是在PO层我需要将它转为List, 如果写方法去适配的话需要写很多,不管是存储,还是查询,都要去适配,user_floor存储的是用,分隔的字符串
实现
原理:继承BaseTypeHandler,去重写里面的抽象方法
PO
autoResultMap这个属性要加,或者说在yaml中配置了,不然查询出来是null
@Data
@TableName(value = "parxxxxxconfig", autoResultMap = true)
@Accessors(chain = true)
public class PaXXXXXXConfigPO {
@TableField(value = "user_floor",typeHandler = ListToStringTypeHandler.class)
private List<Integer> userFloor;
}
handler
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class ListToStringTypeHandler extends BaseTypeHandler<List<Integer>> {
private static final Logger logger = LoggerFactory.getLogger(ListToStringTypeHandler.class);
@Override
public void setNonNullParameter(PreparedStatement ps, int i, List<Integer> parameter, JdbcType jdbcType) throws SQLException {
String value = parameter.stream()
.map(String::valueOf)
.collect(Collectors.joining(","));
logger.info("Setting parameter: {}", value); // 打印日志
ps.setString(i, value);
}
@Override
public List<Integer> getNullableResult(ResultSet rs, String columnName) throws SQLException {
String value = rs.getString(columnName);
logger.info("Getting result from column {}: {}", columnName, value); // 打印日志
return convertStringToList(value);
}
@Override
public List<Integer> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String value = rs.getString(columnIndex);
logger.info("Getting result from column index {}: {}", columnIndex, value); // 打印日志
return convertStringToList(value);
}
@Override
public List<Integer> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String value = cs.getString(columnIndex);
logger.info("Getting result from callable statement: {}", value); // 打印日志
return convertStringToList(value);
}
private List<Integer> convertStringToList(String value) {
if (value == null || value.isEmpty()) {
return Collections.emptyList();
}
return Arrays.stream(value.split(","))
.map(String::trim)
.map(Integer::valueOf)
.collect(Collectors.toList());
}
}
mapper
<resultMap id="xxxxxxConfigMap" type="com.xx.xxx.xxConfigPO">
<result column="config_id" property="configId"/>
<result column="user_floor" property="userFloor" typeHandler="com.cf.newbarcode.dao.handler.ListToStringTypeHandler"/>
</resultMap>
0 条评论