MySQL bigint types and iBATIS对ibatis关于BigInteger不支持的自定义处理方法

MySQL bigint types and iBATIS

One nuance I recently ran into while using iBATIS was inserting data into MySQL bigint unsigned columns. iBATIS doesn’t seem to have a way to handle BigInteger data types and throws an exception when attempting to do an insert. Fetching data out seemed to work OK because if iBATIS doesn’t know how to handle a certain type it just returns a java.lang.Object. The way to go about inserting BigInteger types is to set up a type handler. Here’s an example type handler for BigInteger types:

package org.qnot.util;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.SQLException;
import java.sql.Types;

import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;

public class BigIntegerTypeHandler implements TypeHandlerCallback {

public Object getResult(ResultGetter getter) throws SQLException {
if(getter.wasNull()) {
return null;
}

Object o = getter.getObject();
if(o instanceof BigDecimal) {
BigDecimal bd = (BigDecimal)o;
return bd.toBigInteger();
} else if(o instanceof BigInteger) {
return (BigInteger)o;
} else {
return o;
}
}

public void setParameter(ParameterSetter setter, Object parameter)
throws SQLException {
if (parameter == null) {
setter.setNull(Types.BIGINT);
} else {
BigInteger i = (BigInteger) parameter;
setter.setBigDecimal(new BigDecimal(i));
}
}

public Object valueOf(String s) {
return s;
}
}
Then all you have to do is register the type handler in your sqlmap-config.xml file like so:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<settings useStatementNamespaces="true" />
<typeHandler javaType="java.math.BigInteger"
callback="org.qnot.util.BigIntegerTypeHandler"/>
<sqlMap resource="sql/example.xml"/>
</sqlMapConfig>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值