数据库字段类型设置为json
实体类使用object去接受
自定义json处理器
package io.demo.common.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* json处理器
*/
@MappedTypes(JSONObject.class)
public class JsonTypeHandler extends BaseTypeHandler<JSONObject> {
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, JSONObject jsonObject, JdbcType jdbcType) throws SQLException {
preparedStatement.setString(i, JSON.toJSONString(jsonObject, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat));
}
@Override
public JSONObject getNullableResult(ResultSet resultSet, String s) throws SQLException {
String sqlJson = resultSet.getString(s);
if (sqlJson != null) {
return JSONObject.parseObject(sqlJson);
}
return null;
}
@Override
public JSONObject getNullableResult(ResultSet resultSet, int i) throws SQLException {
String sqlJson = resultSet.getString(i);
if (sqlJson != null) {
return JSONObject.parseObject(sqlJson);
}
return null;
}
@Override
public JSONObject getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
String sqlJson = callableStatement.getString(i);
if (sqlJson != null) {
return JSONObject.parseObject(sqlJson);
}
return null;
}
}
使用方案一(基于mybatis-plus)
通过注解的方式
@ApiModelProperty(value = "参数查询json")
@TableField(typeHandler = JsonTypeHandler.class)
private Object getparamData;
使用方案二(基于xml文件)
新增操作
insert into project_file (idcontent)
values
(#{projectFileEntity.id},#{projectFileEntity.content,jdbcType=OTHER,typeHandler=io.demo.common.config.JsonTypeHandler})
查询操作
<resultMap id="getFileContentMap" type="map">
<result column="content" property="content" typeHandler="io.demo.common.config.JsonTypeHandler"/>
</resultMap>
<select id="getFileContent" resultMap="getFileContentMap">
select content from project_file where data_type=1 and status_id=#{statusId};
</select>