Mybatis自定义类型处理器
mybatis自身拥有丰富的类型处理器,但是在当前网络开发多元化下,一些类型需要根据环境进行定义,简单演示一下mybatis的类型处理器的编辑及使用过程。
创建枚举类型(根据自己需求进行更改)
我用一个人的生存状态做样例,分为年轻、老年、死亡三种状态,对应1、2、3三个数字状态
public enum PeopleType {
/**
* 年轻
*/
YONG(1),
/**
* 年老
*/
OLD(2),
/**
* 去世
*/
DETE(3),;
private int code;
private PeopleType(int code) {
this.code = code;
}
public int getCode() {
return this.code;
}
public static PeopleType valueOf(int code) {
switch (code) {
case 1:
return YONG;
case 2:
return OLD;在这里插入代码片
case 3:
return DETE;
default:
return null;
}
}
}
创建类型处理器
实现TypeHandler接口指定枚举泛型,实现相关方法
public class PeopleTypeHandler implements TypeHandler<PeopleType> {
/**
* 设置数据插入时的类型转换
*/
@Override
public void setParameter(PreparedStatement ps, int i, PeopleType parameter, JdbcType jdbcType) throws SQLException {
// TODO Auto-generated method stub
ps.setInt(i, parameter.getCode());
}
/**
* 设置结果集的数据类型转换
*/
@Override
public PeopleType getResult(ResultSet rs, String columnName) throws SQLException {
int code = rs.getInt(columnName);
return PeopleType.valueOf(code);
}
@Override
public PeopleType getResult(ResultSet rs, int columnIndex) throws SQLException {
int code=rs.getInt(columnIndex);
return PeopleType.valueOf(code);
}
@Override
public PeopleType getResult(CallableStatement cs, int columnIndex) throws SQLException {
int code=cs.getInt(columnIndex);
return PeopleType.valueOf(code);
}
}
配置映射文件,以数据插入为演示案例,数据结果接的获取可用resultMap此处不多解释
<insert id="insertUser" parameterType="com.mybatis.pojo.User">
insert into user(id,username,password,people_type)
values(null,#{username},
#{password},
#{PeopleType,
typeHandler=com.mybatis.typehandler.PeopleTypeHandler})
</insert>
学艺不精,多多指教