1. 程式人生 > 其它 >找不對自定義typeHandler:java.lang.IllegalStateException: No typehandler found for mapping ...

找不對自定義typeHandler:java.lang.IllegalStateException: No typehandler found for mapping ...

1、自定義typeHandler

package com.apollo.cloud.common.core.mybatis.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

/**
 *  儲存到資料庫, 將JSON物件轉換成字串;
 *  從資料庫獲取資料, 將字串轉為JSON物件.
 */
@MappedTypes({JSONObject.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class JsonTypeHandler extends BaseTypeHandler<JSONObject> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, JSONObject parameter,
									JdbcType jdbcType) throws SQLException {

		ps.setString(i, JSONUtil.toJsonStr(parameter));
	}

	@Override
	public JSONObject getNullableResult(ResultSet rs, String columnName)
			throws SQLException {

		return JSONUtil.parseObj(rs.getString(columnName)).toBean(JSONObject.class);
	}

	@Override
	public JSONObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException {

		return JSONUtil.parseObj(rs.getString(columnIndex)).toBean(JSONObject.class);
	}

	@Override
	public JSONObject getNullableResult(CallableStatement cs, int columnIndex)
			throws SQLException {

		return JSONUtil.parseObj(cs.getString(columnIndex)).toBean(JSONObject.class);
	}

}

2、配置包掃描

mybatis-plus:
  type-handlers-package: com.apollo.cloud.common.core.mybatis.typehandler

3、實體使用

import cn.hutool.json.JSONObject;

@Data
@TableName(value = "order_info")
@EqualsAndHashCode(callSuper = true)
@ApiModel(description = "商城訂單")
public class OrderInfo {
	@TableField(typeHandler = JsonTypeHandler.class, jdbcType= JdbcType.VARCHAR)
	private JSONObject payResponse;
}

4、問題原因:實體使用的型別和typeHandler中定義的不一致,型別修改一致問題解決
  實體使用:             

 

   typeHandler定義: