枚举:

spring boot + mybaits 处理枚举类 enum

//实现层调用

orderMapper.getOrder(OrderStatus.DISCOUNT);

sql打印:

实际sql: select * from order where orderStatus = DISCOUNT

预期sql: select * from order where orderSatus = 11;

 

在不使用更改写法

orderMapper.getOrder(OrderStatus.DISCOUNT.getCode());

前提条件下。

源码:org.apache.ibatis.type.BaseTypeHandler  抽象类

 

 

 

spring boot + mybaits 处理枚举类 enum

抽象方法 :

spring boot + mybaits 处理枚举类 enum 

需要重写 继承 BaseTypeHandler 重写方法

package order.handler;

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

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

import common.enums.BaseEnum;

public class StringEnumTypeHandler extends BaseTypeHandler<BaseEnum> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, BaseEnum parameter, JdbcType jdbcType)
            throws SQLException {
     //核心方法 指定枚举获取code的方法。同理 orderMapper.getOrder(OrderStatus.DISCOUNT.getCode());
        ps.setString(i, parameter.getCode().toString());

    }

    @Override
    public BaseEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String val = rs.getString(columnName);
        return getEnum(Integer.parseInt(val));
    }

    @Override
    public BaseEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {

         return getEnum(Integer.parseInt(rs.getString(columnIndex)));
    }

    @Override
    public BaseEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {

        return getEnum(Integer.parseInt(cs.getNString(columnIndex)));
    }

    private BaseEnum getEnum(int val) {
        Class<BaseEnum> sexClass = BaseEnum.class;
        BaseEnum[] sexs = sexClass.getEnumConstants();

        for (BaseEnum se : sexs) {
            if (se.getCode() == val) {
                return se;
            }
        }
        return null;
    }
}

 

 配置mybatis.config 

spring boot + mybaits 处理枚举类 enum

orderMapper.xml

修改前:where type = #{type,jdbcType = int}

修改后:

spring boot + mybaits 处理枚举类 enum

 

基类: 

spring boot + mybaits 处理枚举类 enum

 

所有的枚举都实现这个接口,然后动态加载方法调用枚举的getCode()方法。即可

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-05
  • 2022-12-23
  • 2021-12-11
  • 2022-01-10
  • 2021-04-06
  • 2021-06-12
猜你喜欢
  • 2021-07-02
  • 2022-12-23
  • 2021-09-12
  • 2021-05-17
  • 2021-11-30
  • 2021-12-11
相关资源
相似解决方案