myBatis类型转换器

1.直线 BaseTypeHandler接口
package yang.text.converter;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//转换器 这里是将 java中boolean 转换为数据库中int
public class booleanAndIntConverter extends BaseTypeHandler<Boolean> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType) throws SQLException {
            if(parameter){
                ps.setInt(i,1);
            }else{
                ps.setInt(i,0);
            }
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return  rs.getInt("sex") == 0?true:false;
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return rs.getInt(1) == 0?true:false;
    }

    @Override
    public Boolean getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return cs.getInt(1) == 0?true:false;
    }
}
2.配置xml文件
<typeHandlers>
    <typeHandler handler="yang.text.converter.booleanAndIntConverter" javaType="Boolean" jdbcType="INTEGER"/>
</typeHandlers>
3.因为类中sex属性类型为boolean,表中为int,类型不一致,所以要更改映射文件
<!--因为类中sex属性类型为boolean,表中为int,类型不一致,所以使用resultType-->
    <select id="queryPersonById" resultMap="resultType" parameterType="int">
    select * from person where id = #{id}
      </select>
    <resultMap id="resultType" type="person">
        <id property="id" column="id"/>
        <result property="age" column="age"/>
        <result property="name" column="name"/>
        <result property="sex" column="sex" jdbcType="INTEGER" javaType="boolean"/>
    </resultMap>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值