MyBatis写入Json字段及Json字段转对象
在MyBatis中,要写入JSON字段,你可以将JSON字符串直接作为普通字符串处理。对于从数据库读取JSON字段并转换为Java对象,可以使用TypeHandler
来实现自动转换。
首先,定义一个TypeHandler
来处理JSON字段的读写:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JsonTypeHandler<T> implements TypeHandler<T> {
private static final ObjectMapper mapper = new ObjectMapper();
private Class<T> type;
public JsonTypeHandler(Class<T> type) {
this.type = type;
}
@Override
public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
try {
ps.setString(i, mapper.writeValueAsString(parameter));
} catch (Exception e) {
throw new SQLException("Error converting JSON to String", e);
}
}
@Override
public T getResult(ResultSet rs, String columnName) throws SQLException {
try {
return mapper.readValue(rs.getString(columnName), type);
} catch (IOException e) {
throw new SQLException("Error converting JSON to Object", e);
}
}
@Override
public T getResult(ResultSet rs, int columnIndex) throws SQLException {
try {
return mapper.readValue(rs.getString(columnIndex), type);
} catch (IOException e) {
throw new SQLException("Error converting JSON to Object", e);
}
}
@Override
public T getResult(CallableStatement cs, int columnIndex) throws SQLException {
try {
return mapper.readValue(cs.getString(columnIndex), type);
} catch (IOException e) {
throw new SQLException("Error converting JSON to Object", e);
}
}
}
然后,在MyBatis的配置文件中注册这个TypeHandler
:
<typeHandlers>
<typeHandler handler="com.yourpackage.JsonTypeHandler"/>
</typeHandlers>
最后,在MyBatis的映射文件中使用这个TypeHandler
来处理JSON字段:
<resultMap id="YourResultMap" type="YourType">
<result property="yourJso
评论已关闭