1. 添加新功能
parent
333d728ba8
commit
99706ceb05
@ -0,0 +1,52 @@
|
||||
package com.supervision.police.handler;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.ibatis.type.BaseTypeHandler;
|
||||
import org.apache.ibatis.type.JdbcType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.*;
|
||||
public class JsonTypeHandler<T> extends BaseTypeHandler<T> {
|
||||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private final Class<T> type;
|
||||
|
||||
public JsonTypeHandler(Class<T> type) {
|
||||
if (type == null) throw new IllegalArgumentException("Type argument cannot be null");
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
|
||||
try {
|
||||
ps.setString(i, objectMapper.writeValueAsString(parameter));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
|
||||
String json = rs.getString(columnName);
|
||||
return json == null ? null : parseJson(json);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
|
||||
String json = rs.getString(columnIndex);
|
||||
return json == null ? null : parseJson(json);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
|
||||
String json = cs.getString(columnIndex);
|
||||
return json == null ? null : parseJson(json);
|
||||
}
|
||||
|
||||
private T parseJson(String json) {
|
||||
try {
|
||||
return objectMapper.readValue(json, type);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue