1.字段映射到對象類型java
a.建立handler實現org.apache.ibatis.type.BaseTypeHandlersql
import com.google.gson.Gson; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import java.sql.*; public class ObjectHandler extends BaseTypeHandler<Object> { private static final Gson GSON = new Gson(); @Override public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException { if (parameter == null) { ps.setNull(i, Types.VARCHAR); } else { ps.setString(i, GSON.toJson(parameter)); } } @Override public Object getNullableResult(ResultSet rs, String columnName) throws SQLException { Object convert = convert(rs.getString(columnName)); return convert; } @Override public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException { Object convert = convert(rs.getString(columnIndex)); return convert; } @Override public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { Object convert = convert(cs.getString(columnIndex)); return convert; } private static Object convert(final String columnValue) { return GSON.fromJson(columnValue, Object.class); } }
b.mapper文件中引用數據庫
1).對於select操做,在 resultMap 中進行result配置,指定 typeHandler 便可生效apache
<result property="info" jdbcType="VARCHAR" column="info" typeHandler="com.tencent.iask.util.ObjectHandler"/>
2).對於更新或查詢操做,須要在sql中指定mybatis
<insert id="createTask"> INSERT INTO `task` (`id`,`project`, `priority`, `info`) VALUES (#{id},#{project},#{priority}, #{info,typeHandler=ObjectHandler}); </insert>
2. 使用了typehandler找不到構造函數的問題app
Caused by: org.apache.ibatis.executor.ExecutorException: No constructor found in com.model.Task matching [java.lang.Integer, java.lang.String, java.lang.Integer, java.lang.String]
個人Task類,定義以下(info字段映射的數據庫字段類型爲varchar):ide
@Slf4j @Data @AllArgsConstructor public class Task { private Integer id; private String project; private int priority; private Object info; }
緣由爲:mybatis默認使用無參構造函數,若是沒有此函數會根據數據庫字段類型尋找有參構造函數,此時,若是對象只有成員列表對應有參構造函數,那麼會報找不到構造函數的錯誤,所以在使用typehandler時,最好給數據類型一個無參構造函數。函數