I'm trying to configure a default IntegerTypeHandler
from org.apache.ibatis.type
package of MyBatis 3.2.1
on one of my result maps.
Given the following constructor signature:
public Activity(int id, String name, String color, ActivityType type,
int idOfOwnerClient) {
//validations and fields initializations
}
I'm trying to transform a SQL NULL
value to an int
with value 0
, because the field int idOfOwnerClient
is optional, so, the database may have NULL
values.
If a try to pass a null
to a primitive type like int
, an Exception
will be thown, to solve that, I'm configuring a TypeHandler
.
Here's a snippet of my mybatis-config.xml
<configuration>
<typeAliases>
<typeAlias alias="intTypeHandler" type="org.apache.ibatis.type.IntegerTypeHandler"/>
</typeAliases>
</configuration>
and a snippet of my result map (notice the type handler of last arg element):
<resultMap type="Activity" id="activityResult">
<constructor>
<idArg column="activity.id" javaType="_int"/>
<arg column="activity.name" javaType="String"/>
<arg column="activity.color" javaType="String"/>
<arg resultMap="ActivityTypeMapper.activityTypeResult" javaType="ActivityType"/>
<arg column="activity.id_client" javaType="_int" typeHandler="intTypeHandler"/>
</constructor>
</resultMap>
But, when I run a junit test, I get the following error (notice the null
value at the end of the error):
org.mybatis.spring.MyBatisSystemException: nested exception is
org.apache.ibatis.reflection.ReflectionException: Error instantiating class
br.com.agrofficio.kpifarm.model.Activity with invalid types
(int,String,String,ActivityType,int,) or values
(2,Aplicação de Cal,FFFFFF,[Id: 1, Name: Plantio],null,). Cause: java.lang.IllegalArgumentException
As the stacktrace above proposes, I'm still getting a null
value instead of 0
, even with the handler applied.
Solutions that I tried with no success
1. Using the fully qualified name of the handler intead an alias on resultmap:
<arg column="activity.id_client" javaType="_int" typeHandler="org.apache.ibatis.type.IntegerTypeHandler"/>
2. Adding a type handler declaration on mybatis-config.xml
:
<typeHandlers>
<typeHandler handler="org.apache.ibatis.type.IntegerTypeHandler"/>
</typeHandlers>
Any ideas? Thanks in advance!
You get exceptions because you are trying to use Mybatis' default IntegerTypeHandler
, which doesn't support null values (source code).
In order to satisfy your requirements, you need to implement custom typeHandler, which will inherit from default IntegerTypeHandler
.
Here you'll find all information needed to implement your own typeHandler.
If you don't know where to start with your own typeHandler: This class is nearly exactly what you want. Looking at its interface makes it clear that:
you should extend the default org.apache.ibatis.type.IntegerTypeHandler
in your implementation both getResult()
methods should be overriden