|
| 1 | +package top.cadecode.uniboot.common.mybatis.handler; |
| 2 | + |
| 3 | +import org.apache.ibatis.type.BaseTypeHandler; |
| 4 | +import org.apache.ibatis.type.JdbcType; |
| 5 | +import org.apache.ibatis.type.MappedJdbcTypes; |
| 6 | +import org.apache.ibatis.type.MappedTypes; |
| 7 | +import top.cadecode.uniboot.common.util.JacksonUtil; |
| 8 | + |
| 9 | +import java.sql.CallableStatement; |
| 10 | +import java.sql.PreparedStatement; |
| 11 | +import java.sql.ResultSet; |
| 12 | +import java.sql.SQLException; |
| 13 | +import java.util.List; |
| 14 | + |
| 15 | +/** |
| 16 | + * java 对象和 db varchar 转换,即 json 转换 |
| 17 | + * |
| 18 | + * @author Cade Li |
| 19 | + * @since 2023/5/10 |
| 20 | + */ |
| 21 | +@MappedTypes({Object.class, List.class}) |
| 22 | +@MappedJdbcTypes(JdbcType.VARCHAR) |
| 23 | +public class ObjToStrTypeHandler extends BaseTypeHandler<Object> { |
| 24 | + |
| 25 | + private final Class<?> type; |
| 26 | + |
| 27 | + public ObjToStrTypeHandler(Class<?> type) { |
| 28 | + this.type = type; |
| 29 | + } |
| 30 | + |
| 31 | + @Override |
| 32 | + public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException { |
| 33 | + ps.setString(i, JacksonUtil.toJson(parameter)); |
| 34 | + } |
| 35 | + |
| 36 | + @Override |
| 37 | + public Object getNullableResult(ResultSet rs, String columnName) throws SQLException { |
| 38 | + final String json = rs.getString(columnName); |
| 39 | + return JacksonUtil.toBean(json, type); |
| 40 | + } |
| 41 | + |
| 42 | + @Override |
| 43 | + public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException { |
| 44 | + final String json = rs.getString(columnIndex); |
| 45 | + return JacksonUtil.toBean(json, type); |
| 46 | + } |
| 47 | + |
| 48 | + @Override |
| 49 | + public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { |
| 50 | + final String json = cs.getString(columnIndex); |
| 51 | + return JacksonUtil.toBean(json, type); |
| 52 | + } |
| 53 | +} |
0 commit comments