io.github.jinghui70.rainbow.dbaccess.fieldmapper.ClobObjectFieldMapper Maven / Gradle / Ivy
The newest version!
package io.github.jinghui70.rainbow.dbaccess.fieldmapper;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class ClobObjectFieldMapper extends FieldMapper {
private final Class fieldClass;
private Class> componentClass;
public ClobObjectFieldMapper(Class fieldClass, Field field) {
this.fieldClass = fieldClass;
if (fieldClass.isArray())
componentClass = fieldClass.getComponentType();
else if (field!=null && fieldClass.isAssignableFrom(List.class)) {
ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
componentClass = (Class>) actualTypeArguments[0];
}
}
@Override
@SuppressWarnings("unchecked")
public T formDB(ResultSet rs, int index) throws SQLException {
String json = rs.getString(index);
if (rs.wasNull()) return null;
if (fieldClass.isArray()) {
JSONArray array = JSONUtil.parseArray(json);
return (T) array.toArray(componentClass);
}
if (fieldClass.isAssignableFrom(List.class)) {
JSONArray array = JSONUtil.parseArray(json);
return (T) array.toList(componentClass);
}
return JSONUtil.toBean(json, fieldClass);
}
@Override
public void saveToDB(PreparedStatement ps, int paramIndex, Object value) throws SQLException {
String json = JSONUtil.toJsonStr(value);
ps.setString(paramIndex, json);
}
public static ClobObjectFieldMapper of(Class fieldClass) {
return new ClobObjectFieldMapper<>(fieldClass, null);
}
@SuppressWarnings("unchecked")
public static ClobObjectFieldMapper> ofList(Class componentClass) {
ClobObjectFieldMapper> result = new ClobObjectFieldMapper<>(List.class, null);
result.componentClass = componentClass;
return (ClobObjectFieldMapper>) result;
}
@SuppressWarnings("unchecked")
public static ClobObjectFieldMapper ofArray(Class componentClass) {
ClobObjectFieldMapper> result = new ClobObjectFieldMapper<>(Object[].class, null);
result.componentClass = componentClass;
return (ClobObjectFieldMapper) result;
}
}