Mybaits自定义类型处理器

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>

学艺不精,多多指教

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值