MyBatis when a parameter is set in a preprocessing statement (PreparedStatement), or when a value is fetched from the result set, the value obtained by the type processor is converted to the Java type in the appropriate way. MyBatis default for us to implement a lot of typehandler, when we do not configure the specified Typehandler, mybatis depending on the parameters or return the results of the difference, the default for us to choose the appropriate typehandler processing.
How do we configure a custom Typehandler?
Mappedjdbctypes ({Jdbctype.varchar})
Mappedtypes ({string[].class})
public class Stringarraytypehandler implements typehandler<string[]> {//. The middle implementation code is omitted//. }
One: Register Typehandler
This is registered in the MyBatis configuration file.
<typeHandlers>
<typehandler handler= "Com.jstudio.mybatis.handler.StringArrayTypeHandler" jdbctype= "VARCHAR" javatype= "[ Ljava.lang.String; " />
</typeHandlers>
Configure directly in spring's configuration file
<!--configuration Sqlsessionfactory--
<bean id= "Sqlsessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" >
<!--automatically scan Mapper files, the pretext for naming and *mapper.xml consistent! -
<property name= "mapperlocations" value= "Classpath:org/jstudioframework/freeway/**/mapper/*mapper.xml"/>
<property name= "DataSource" ref= "DataSource"/>
<!--configuration MyBatis plug-in plugin-->
<property name= "Plugins" >
<list>
<ref bean= "Paginationinterceptor"/>
<ref bean= "Sqlstatementmonitorinterceptor"/>
</list>
</property>
<property name= "Typehandlers" >
<list>
<bean class= "Org.jstudioframework.mybatis.type.StringTokenizerLongTypeHandler"/>
</list>
</property>
</bean>
II: Use in Mapper.xml
Define the corresponding column in the definition of Resultmap Typehandler
<resultmap type= "Note" id= "Baseresultmap" >
<result property= "id" column= "id"/>
<result property= "Names" column= "names" jdbctype= "VARCHAR" javatype= "[java.lang.String;"
Typehandler= "Demo. Stringarraytypehandler "/>
</resultMap>
This is the only time that a custom typehandler is used to process the corresponding mapping relationship, and if you want to use it at insert or update, you need to add the appropriate content to the SQL definition. As follows:
<update id= "Updatenames" parametertype= "User" >
Update user
Set Names=#{names, javatype=[java.lang.string;, Jdbctype=varchar}
Where Id=#{id}
</update>
If the Jdbctype and javatype that are registered with Typehandler are displayed, the following methods are available
<update id= "Updatenames" parametertype= "User" >
Update user
Set Names=#{names,typehandler=demo. Stringarraytypehandler}
Where Id=#{id}
</update>