标签:handle extends resultset null pre apache 信息 struct 转换
在一些时候,我们的数据库需要存放一些例如状态信息的数据,通常的我们使用int整型来保存,例如(0:失败,1:成功)等,用这样的数据是可以的,但对于前端的编程是不友好的,所以我们可以使用TypeHandler来进行一个转换,将其转化成一个枚举型。
这里的user_state和user_priority表示了一些状态信息(范围是整数0~5),接下来我们要将这个转化为枚举型
以User_state为例:
package com.snapshot2.demo.enumeration; public enum UserStateEnum { NORMAL(0,"正常状态"), FROZEN(1,"冻结"), BAN(2,"禁用"), MUTE(3,"禁言"), SENSITIVE(4,"敏感用户"), DYF(5,"这是创作者董一帆的"); private int stateCode; private String stateString; public static UserStateEnum getUserStateByCode(int stateCode){ for (UserStateEnum stateEnum: values()){ if(stateEnum.getStateCode() == stateCode){ return stateEnum; } } return null; } /* Constructor */ UserStateEnum(int stateCode, String stateString) { this.stateCode = stateCode; this.stateString = stateString; } /* Getter and Setter */ public int getStateCode() { return stateCode; } public void setStateCode(int stateCode) { this.stateCode = stateCode; } public String getStateString() { return stateString; } public void setStateString(String stateString) { this.stateString = stateString; } }
1.这里的<T>是我们指定转化的类型
2.@MappedJdbcTypes注解声明数据库中对应数据类型
3.@MappedTypes(value = UserStateEnum.class)声明转化后的类型
package com.snapshot2.demo.typehandler; import com.snapshot2.demo.enumeration.UserStateEnum; 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.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /* 数据库中的数据类型 */ @MappedJdbcTypes(JdbcType.INTEGER) /* 转化后的数据类型 */ @MappedTypes(value = UserStateEnum.class) public class UserStateTypeHandler extends BaseTypeHandler<UserStateEnum> { @Override public void setNonNullParameter(PreparedStatement preparedStatement, int i, UserStateEnum userStateEnum, JdbcType jdbcType) throws SQLException { preparedStatement.setInt(i,userStateEnum.getStateCode()); } @Override public UserStateEnum getNullableResult(ResultSet resultSet, String s) throws SQLException { int code =resultSet.getInt(s); if(code>=0&&code<=5){ return UserStateEnum.getUserStateByCode(code); } return null; } @Override public UserStateEnum getNullableResult(ResultSet resultSet, int i) throws SQLException { int code = resultSet.getInt(i); if(code>=0&&code<=5){ return UserStateEnum.getUserStateByCode(code); } return null; } @Override public UserStateEnum getNullableResult(CallableStatement callableStatement, int i) throws SQLException { int code = callableStatement.getInt(i); if(code>=0&&code<=5){ return UserStateEnum.getUserStateByCode(code); } return null; } }
mybatis.type-handlers-package=com.snapshot2.demo.typehandler
Springboot整合Mybatis使用TypeHandler来转换数据库中的数据
标签:handle extends resultset null pre apache 信息 struct 转换
原文地址:https://www.cnblogs.com/dyf-stu/p/10162301.html