diff --git a/src/main/java/cn/axzo/pokonyan/config/mybatisplus/type/BaseListTypeHandler.java b/src/main/java/cn/axzo/pokonyan/config/mybatisplus/type/BaseListTypeHandler.java new file mode 100644 index 0000000..9f10a5e --- /dev/null +++ b/src/main/java/cn/axzo/pokonyan/config/mybatisplus/type/BaseListTypeHandler.java @@ -0,0 +1,54 @@ +package cn.axzo.pokonyan.config.mybatisplus.type; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.serializer.SerializerFeature; +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; +import org.apache.ibatis.type.MappedJdbcTypes; +import org.apache.ibatis.type.MappedTypes; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + +/** + * @author haiyangjin + * @date 2023/9/13 + */ +@MappedTypes({List.class}) +@MappedJdbcTypes(JdbcType.VARCHAR) +public abstract class BaseListTypeHandler extends BaseTypeHandler> { + private Class type = getGenericType(); + + @Override + public void setNonNullParameter(PreparedStatement preparedStatement, int i, + List list, JdbcType jdbcType) throws SQLException { + preparedStatement.setString(i, JSONArray.toJSONString(list, SerializerFeature.WriteMapNullValue, + SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty)); + } + + @Override + public List getNullableResult(ResultSet resultSet, String s) throws SQLException { + return JSONArray.parseArray(resultSet.getString(s), type); + } + + @Override + public List getNullableResult(ResultSet resultSet, int i) throws SQLException { + return JSONArray.parseArray(resultSet.getString(i), type); + } + + @Override + public List getNullableResult(CallableStatement callableStatement, int i) throws SQLException { + return JSONArray.parseArray(callableStatement.getString(i), type); + } + + private Class getGenericType() { + Type t = getClass().getGenericSuperclass(); + Type[] params = ((ParameterizedType) t).getActualTypeArguments(); + return (Class) params[0]; + } +} diff --git a/src/main/java/cn/axzo/pokonyan/config/mybatisplus/type/LongListTypeHandler.java b/src/main/java/cn/axzo/pokonyan/config/mybatisplus/type/LongListTypeHandler.java new file mode 100644 index 0000000..df911e0 --- /dev/null +++ b/src/main/java/cn/axzo/pokonyan/config/mybatisplus/type/LongListTypeHandler.java @@ -0,0 +1,8 @@ +package cn.axzo.pokonyan.config.mybatisplus.type; + +/** + * @author haiyangjin + * @date 2023/9/13 + */ +public class LongListTypeHandler extends BaseListTypeHandler { +}