定义一个枚举类
public enum KbnEnum {
UNAUDITED(0, "未审核"),
AUDIT(1, "待审核"),
AUDITED(2, "已审核");
private int code;
public int getCode() {
return code;
}
private String name;
public String getName() {
return name;
}
KbnEnum(int code, String name) {
this.code = code;
this.name = name;
}
public static KbnEnum fromCode(int code) {
for (KbnEnum item : KbnEnum.values()) {
if (item.code == code) {
return item;
}
}
return null;
}
}
定义一个类型转换器
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 org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
// 导入我们自定义的枚举类
import com.xxx.KbnEnum;
// 数据库字段所对应的类型
@MappedJdbcTypes({JdbcType.NUMERIC})
// 需要转换为JAVA侧的类型
@MappedTypes(value = KbnEnum.class)
// 进行类型转换需要继承Mybatis的BaseTypeHandler类
public class CustomEnumTypeHandler extends BaseTypeHandler<KbnEnum> {
// 重写BaseTypeHandler中的方法
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, KbnEnum parameter, JdbcType jdbcType) throws SQLException {
preparedStatement.setInt(i, parameter.getCode());
}
@Override
public KbnEnum getNullableResult(ResultSet resultSet, String s) throws SQLException {
String code = resultSet.getString(s);
return KbnEnum.fromCode(Integer.valueOf(code));
}
@Override
public KbnEnum getNullableResult(ResultSet resultSet, int i) throws SQLException {
String code = resultSet.getString(i);
return KbnEnum.fromCode(Integer.valueOf(code));
}
@Override
public KbnEnum getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
String code = callableStatement.getString(i);
return KbnEnum.fromCode(Integer.valueOf(code));
}
}
将自定义转换器添加到Mybatis转换器中
⏹方式1,在SpringBoot的配置文件中声明
mybatis.type-handlers-package=com.xxx.xxx.config
⏹方式2,在进行类型映射的时候,手动指定转换器
<resultMap id="userResultMap" type="com.xxx.dto.TestDto">
<result column="JHE_KEIYAKUKBN" property="kbnEnum" typeHandler="com.xxx.config.CustomEnumTypeHandler" />
</resultMap>
<select id="testT" resultMap="userResultMap">
SELECT
JHE_KEIYAKUKBN
FROM
JUHEDF
WHERE
JHE_SIMEINO = 1
</select>
查询
可以看到成功将数字0封装为枚举类
参考资料
- 👍👍👍https://blog.csdn.net/lmb55/article/details/90380309
- https://zhuanlan.zhihu.com/p/245448322
- http://www.itsoku.com/article/194