MybatisPlus保存Json数据
接收的json数据里面是数组形式,因此接收格式定义为List;
@Data
@TableName(value = "user", autoResultMap = true)
public class IbcEmergencyPlanProcess extends Model<IbcEmergencyPlanProcess> {
private static final long serialVersionUID = 1L;
@TableId
private Integer id;
private String name;
@Transient
@TableField(jdbcType = JdbcType.VARCHAR, insertStrategy = NOT_NULL, typeHandler = ListToStringHandler.class)
private List jsonInfo;
}
使用MybatisPlus提供的save方法,xml定义为如下:
<resultMap id="map" type="com.entity.User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="jsonInfo" column="json_info" typeHandler="com.controller.ListToStringHandler"/>
</resultMap>
需要定义一个Json转换类,查询的时候需要给json格式的数据定义一个typeHandler
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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.List;
/**
* list转换string
*/
public class ListToStringHandler extends BaseTypeHandler<List> {
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, List list, JdbcType jdbcType) throws SQLException {
preparedStatement.setString(i, JSON.toJSONString(list));
}
@Override
public List getNullableResult(ResultSet resultSet, String s) throws SQLException {
JSONArray jsonArray = JSONArray.parseArray( resultSet.getString(s));
return jsonArray;
}
@Override
public List getNullableResult(ResultSet resultSet, int i) throws SQLException {
JSONArray jsonArray = JSONArray.parseArray( resultSet.getString(i));
return jsonArray;
}
@Override
public List getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
JSONArray jsonArray = JSONArray.parseArray( callableStatement.getString(i));
return jsonArray;
}
}