Mybatis自动注册TypeHandler,自动扫描、自定义注解实现自定义TypeHandler

上一篇手动版https://blog.csdn.net/h785160953/article/details/103615458

自定义的TypeHandler

  • 1、JsonTypeHandler.java


import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库字段string - Java对象互转handler
 *
 * @author Leo.Xi
 * @date 2019/12/18
 * @since 1.0
 **/
@MappedJdbcTypes({
   JdbcType.VARCHAR, JdbcType.CHAR, JdbcType.NCHAR, JdbcType.LONGVARCHAR})
public class JsonTypeHandler<T extends Object> extends BaseTypeHandler<T> {
   

    public static final String ID_TEMPLATE = "{\"id\":\"%s\"}";

    private Class<? extends T> clazz;// clazz
    private DwDaoHandler.Type type;// 序列化类型

    public JsonTypeHandler(Class<? extends T> clazz) {
   
        if (clazz == null) {
   
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.clazz = clazz;
        this.type = DwMybatisConfig.getSingleType(clazz);
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
   
        if (DwDaoHandler.Type.JSON.equals(type)) {
    // JSON
            ps.setString(i, JsonUtils.toNoNullJsonStr(parameter));
        } else {
   
            ps.setString(i, ((BaseDomain) parameter).getId());
        }
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
   
        if (DwDaoHandler.Type.JSON.equals(type)) {
    // JSON
            return JsonUtils.readValue(rs.getString(columnName), clazz);
        } else {
   
            return JsonUtils.readValue(String.format(ID_TEMPLATE, rs.getString(columnName)), clazz);
        }
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
   
        if (DwDaoHandler.Type.JSON.equals(type)) {
    // JSON
            return JsonUtils.readValue(rs.getString(columnIndex), clazz);
        } else {
   
            return JsonUtils.readValue(String.format(ID_TEMPLATE, rs.getString(columnIndex)), clazz);
        }
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
   
        if (DwDaoHandler.Type.JSON.equals(type)) {
    // JSON
            return JsonUtils.readValue(cs.getString(columnIndex), clazz);
        } else {
   
            return JsonUtils.readValue(String.format(ID_TEMPLATE, cs.getString(columnIndex)), clazz);
        }
    }

}
  • 2、JsonListTypeHandler.java


import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据库字段string - Java对象互转handler
 *
 * @author Leo.Xi
 * @date 2019/12/18
 * @since 1.0
 **/
@MappedJdbcTypes({
   JdbcType.VARCHAR, JdbcType.CHAR, JdbcType.NCHAR, JdbcType.LONGVARCHAR})
public class JsonListTypeHandler<T extends Object> extends BaseTypeHandler<List<T>> {
   

    private Class<? extends T> clazz;// clazz
    private DwDaoHandler.Type type;// 序列化类型

    public JsonListTypeHandler(Class<? extends T> clazz) {
   
        if (clazz == null) {
   
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.clazz = clazz;
        this.type = DwMybatisConfig.getCollectionType(clazz);
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<T> parameter, JdbcType jdbcType) throws SQLException {
   
        if (DwDaoHandler.Type.JSON.equals(type)) {
    // JSON
            ps.setString(i, JsonUtils.toNoNullJsonStr(parameter));
        } else {
   
            String value = parameter.stream().map(x -> (BaseDomain) x).map(BaseDomain::getId).collect(Collectors.joining(
                    ","));
            ps.setString(i, value);
        }
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
   
        String value = rs.getString(columnName);
        if (value == null) {
   
            return null;
        }
        List<T> result = new LinkedList<>();
        if (DwDaoHandler.Type.JSON.equals(type)) {
    // JSON
            List<T> ts = JsonUtils.readValue(value, new TypeReference<List<T>>() {
   
            });
            if (ts != null) {
   
                ts.forEach(x -> {
   
                    T t = JsonUtils.convertValue(x, clazz);
                    if(null == t){
   
                        // throw RuntimeException
                    } else {
   
                        result.add(t);
                    }
                });
                return result;
            }
        } else {
   
            String[] ids = value.split
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot和MyBatis Plus一起使用时,可以使用TypeHandler来处理数据库中的自定义类型和Java对象之间的转换。 首先,您需要创建一个自定义TypeHandler类来处理特定类型的转换。例如,假设您有一个名为CustomType自定义类型,您可以创建一个CustomTypeHandler类来处理它的转换。 ```java 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; public class CustomTypeHandler extends BaseTypeHandler<CustomType> { @Override public void setNonNullParameter(PreparedStatement preparedStatement, int i, CustomType customType, JdbcType jdbcType) throws SQLException { preparedStatement.setString(i, customType.toString()); } @Override public CustomType getNullableResult(ResultSet resultSet, String s) throws SQLException { return CustomType.fromString(resultSet.getString(s)); } @Override public CustomType getNullableResult(ResultSet resultSet, int i) throws SQLException { return CustomType.fromString(resultSet.getString(i)); } @Override public CustomType getNullableResult(CallableStatement callableStatement, int i) throws SQLException { return CustomType.fromString(callableStatement.getString(i)); } } ``` 在这个例子中,CustomTypeHandler继承自MyBatis中的BaseTypeHandler,并重写了一些方法来实现类型转换。setNonNullParameter方法用于将Java对象转换为数据库中的值,getNullableResult方法用于将数据库中的值转换为Java对象。 接下来,在您的实体类中使用@TableField注解来指定字段使用自定义TypeHandler。例如: ```java public class MyEntity { @TableField(typeHandler = CustomTypeHandler.class) private CustomType customType; // 其他字段和方法... } ``` 最后,您需要在MyBatis的配置文件中注册自定义TypeHandler。在application.properties或application.yml中添加以下配置: ```yaml mybatis-plus: configuration: map-underscore-to-camel-case: true type-handlers-package: com.example.typehandler ``` 这里的`com.example.typehandler`是您自定义TypeHandler类的包路径。 通过这些步骤,您就可以在Spring Boot中使用MyBatis Plus的TypeHandler来处理自定义类型和Java对象之间的转换了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值