MyBatis-plus 新增时List转String 查询时String转list
1. 需求说明
项目为:SpringBoot+MyBatisPlus
采用实体类接受参数,有一个参数为List
List
2.具体操作
- 新增自定义的typeHandler,继承BaseTypeHandler,具体代码如下:
package com.zjjg.dlbp.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springblade.core.tool.utils.ObjectUtil;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* List<Integer> ==> string
* @Date 2022-10-08
*/
public class ListToStringHandle extends BaseTypeHandler<List> {
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, List list, JdbcType jdbcType) throws SQLException {
if (ObjectUtil.isNotEmpty(list)){
preparedStatement.setString(i, JSON.toJSONString(list));
}
}
@Override
public List getNullableResult(ResultSet resultSet, String s) throws SQLException {
String result = resultSet.getString(s);
return result ==null? new ArrayList<>():JSONArray.parseArray(result);
}
@Override
public List getNullableResult(ResultSet resultSet, int i) throws SQLException {
String result = resultSet.getString(i);
return result ==null? new ArrayList<>():JSONArray.parseArray(result);
}
@Override
public List getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
String result = callableStatement.getString(i);
return result ==null? new ArrayList<>():JSONArray.parseArray(result);
}
}
-
在数据库对应实体类字段上增加注解
@TableField(jdbcType = JdbcType.VARCHAR,typeHandler = ListToStringHandle.class) private List<Integer> protectiveFacility; @TableField(jdbcType = JdbcType.VARCHAR,typeHandler = ListToStringHandle.class) private List<Integer> drainageFacility;
-
在mapper.xml中 对应字段上添加typeHandler
<result column="drainage_facility" property="drainageFacility" typeHandler="com.zjjg.dlbp.config.ListToStringHandle"/> <result column="protective_facility" property="protectiveFacility" typeHandler="com.zjjg.dlbp.config.ListToStringHandle"/>
-
在application.yml文件中,增加 type-handlers-package配置,设置typeHandle所在包位置
mybatis-plus: type-handlers-package: com.app.config