58 lines
1.5 KiB
Java
58 lines
1.5 KiB
Java
package com.imyeyu.api.handler;
|
|
|
|
import com.google.gson.JsonElement;
|
|
import com.google.gson.JsonParser;
|
|
import com.imyeyu.java.TimiJava;
|
|
import org.apache.ibatis.type.BaseTypeHandler;
|
|
import org.apache.ibatis.type.JdbcType;
|
|
|
|
import java.sql.CallableStatement;
|
|
import java.sql.PreparedStatement;
|
|
import java.sql.ResultSet;
|
|
import java.sql.SQLException;
|
|
|
|
/**
|
|
* MySQL JSON 数据类型处理器
|
|
*
|
|
* @author 夜雨
|
|
* @since 2021-07-04 09:36
|
|
*/
|
|
public class GsonHandler extends BaseTypeHandler<JsonElement> {
|
|
|
|
@Override
|
|
public void setNonNullParameter(PreparedStatement ps, int i, JsonElement parameter, JdbcType jdbcType) throws SQLException {
|
|
ps.setString(i, String.valueOf(parameter.toString()));
|
|
}
|
|
|
|
@Override
|
|
public JsonElement getNullableResult(ResultSet rs, String columnName) throws SQLException {
|
|
return toElement(rs.getString(columnName));
|
|
}
|
|
|
|
@Override
|
|
public JsonElement getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
|
|
return toElement(rs.getString(columnIndex));
|
|
}
|
|
|
|
@Override
|
|
public JsonElement getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
|
|
return toElement(cs.getNString(columnIndex));
|
|
}
|
|
|
|
private JsonElement toElement(String json) {
|
|
if (TimiJava.isNotEmpty(json)) {
|
|
JsonElement el = JsonParser.parseString(json);
|
|
if (el.isJsonObject()) {
|
|
return el.getAsJsonObject();
|
|
}
|
|
if (el.isJsonArray()) {
|
|
return el.getAsJsonArray();
|
|
}
|
|
if (el.isJsonPrimitive()) {
|
|
return el.getAsJsonPrimitive();
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
}
|