mybatis如何將結果轉為對象?
mybaits將結果轉為對象的方法主要有將SQL發送到了數據庫,并返回了ResultSet,接下來就是將結果集 ResultSet 自動映射成實體類對象。這樣使用者就無需再手動操作結果集,并將數據填充到實體。
/*** @ClassName: JsonTypeHandler
* @Description:
* mapper里json型字段到類的映射。
* 入庫:#{jsonDataField, typeHandler=com.yx.smp.basic.handler.JsonTypeHandler}
* 出庫:
* <resultMap type="com.yx.smp.business.accuracy.model.domain.SmpAccuracyRecord" id="SmpAccuracyRecordMap">
* <result property="accuracyJson" column="accuracy_Json" javaType="com.yx.smp.business.accuracy.model.domain.AccuracyJson" typeHandler="com.yx.smp.basic.handler.JsonTypeHandler"/>
* </resultMap>
* @Author: RuiXin Yu
* @Date: 2019/2/22 16:23
*/
public class JsonTypeHandler<T extends Object> extends BaseTypeHandler<T> {
private static final ObjectMapper mapper = new ObjectMapper();
private Class<T> clazz;
static {
mapper.configure(Feature.WRITE_NULL_MAP_VALUES, false);
}
public JsonTypeHandler(Class<T> clazz) {
if (clazz == null){
throw new IllegalArgumentException("Type argument cannot be null");
}
this.clazz = clazz;
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, this.toJson(parameter));
}
@Override
public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
return this.toObject(rs.getString(columnName), clazz);
}
@Override
public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return this.toObject(rs.getString(columnIndex), clazz);
}
@Override
public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return this.toObject(cs.getString(columnIndex), clazz);
}
private String toJson(T object) {
try {
return mapper.writeValueAsString(object);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private T toObject(String content, Class<?> clazz) {
if (content != null && !content.isEmpty()) {
try {
return (T) mapper.readValue(content, clazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
return null;
}
}
}?