mybatis如何将结果转为对象?
mybaits将结果转为对象的方法主要有将SQL发送到了数据库,并返回了ResultSet,接下来就是将结果集 ResultSet 自动映射成实体类对象。这样使用者就无需再手动操作结果集,并将数据填充到实体。
/*** @ClassName: JsonTypeHandler
* @Description:
* mapper里json型字段到类的映射。
* 入库:#{jsonDataField, typeHandler=com.yx.smp.basic.handler.JsonTypeHandler}
* 出库:
*
*
*
* @Author: RuiXin Yu
* @Date: 2019/2/22 16:23
*/
public class JsonTypeHandler
private static final ObjectMapper mapper = new ObjectMapper();
private Class
static {
mapper.configure(Feature.WRITE_NULL_MAP_VALUES, false);
}
public JsonTypeHandler(Class
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;
}
}
}?