Business extension fields are often stored in json format in the PostgreSQL database. However, mybatis does not implement the TypeHandler corresponding to the json type field by default, so generally we need to customize the TypeHandler of mybatis.
The following is a simple implementation of TypeHandler corresponding to the json type field in mybatis:
import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.MappedTypes; import org.postgresql.util.PGobject; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @MappedTypes({Object.class}) public class JsonTypeHandler extends BaseTypeHandler<Object> { private static final PGobject jsonObject = new PGobject(); @Override public void setNonNullParameter(PreparedStatement preparedStatement, int i, Object o, JdbcType jdbcType) throws SQLException { jsonObject.setType("json"); jsonObject.setValue(JsonUtil.toJsonString(o)); preparedStatement.setObject(i, jsonObject); } @Override public Object getNullableResult(ResultSet resultSet, String s) throws SQLException { return JsonUtil.fromJson(resultSet.getString(s), Object.class); } @Override public Object getNullableResult(ResultSet resultSet, int i) throws SQLException { return JsonUtil.fromJson(resultSet.getString(i), Object.class); } @Override public Object getNullableResult(CallableStatement callableStatement, int i) throws SQLException { return JsonUtil.fromJson(callableStatement.getString(i), Object.class); } }
In addition to writing TypeHandler, the following configuration needs to be done in the xml mapping file:
<resultMap id="BaseResultMap" type="com.test.entity.EventLog"> <id column="uuid" jdbcType="VARCHAR" property="uuid"/> <result column="payload" jdbcType="OTHER" property="payload" typeHandler="com.test.dao.typehandler.JsonTypeHandler"/> </resultMap>
<insert id="insert" parameterType="com.test.entity.EventLog"> insert into "test".event_log (uuid,payload) values (#{uuid,jdbcType=VARCHAR},#{payload,jdbcType=OTHER,typeHandler=com.test.dao.typehandler.JsonTypeHandler}) </insert>
When using, after obtaining the Object object, it can be converted into a json string first, and then converted into the corresponding object, as follows:
EventLogPayload eventLogPayload = JsonUtil.parser(JsonUtil.toJson(eventLog.getPayload()), EventLogPayload.class);