枚举:
//实现层调用
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 抽象类
抽象方法 :
需要重写 继承 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
orderMapper.xml
修改前:where type = #{type,jdbcType = int}
修改后:
基类:
所有的枚举都实现这个接口,然后动态加载方法调用枚举的getCode()方法。即可
原文地址:https://www.cnblogs.com/1-Admin/p/10863703.html
时间: 2024-10-03 16:49:23