Use an implicit TypeHandler based on resultType for select in MyBatis

1,675 views
Skip to first unread message

Shobit Beltangdy

unread,
Jun 2, 2015, 1:54:31 AM6/2/15
to mybati...@googlegroups.com
Hi mybatis-users,

There's a question on StackOverflow that I came across related to implicitly using a custom typeHandler.  Since I am facing the same issue, I thought I should create a new topic and link the question below so that someone can respond to it (it's got a +50 reputation bounty ending in 7 days!)

http://stackoverflow.com/questions/30307031/use-an-implicit-typehandler-based-on-resulttype-for-select-in-mybatis

I'd appreciate your help.  Thanks.

Ikchan Sim

unread,
Jun 2, 2015, 2:45:35 AM6/2/15
to mybati...@googlegroups.com
Used by <resultMap /> :

/* MyBatis Configuration XML File */
<typeHandlers>
    <typeHandler jdbcType="java.sql.Timestamp" javaType="org.joda.time.LocalDateTime" handler="...LocalDateTimeTypeHandler"/>
</typeHandlers>


/* Mapper Interface */
import org.joda.time.LocalDateTime;

public interface NotifMailDao {
    LocalDateTime getLastNotifTime();
}


/* MyBatis Mapper XML File */
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 

<mapper namespace="lu.bgl.notif.mail.dao.NotifMailDao">
    <resultMap id="notifMailResultMap" type="org.joda.time.LocalDateTime">
        <result column="LAST_TIME" property="lastTime" jdbcType="java.sql.Timestamp" javaType="org.joda.time.LocalDateTime" />
    </resultMap>

    <select id="getLastNotifTime" resultMap="notifMailResultMap">
        SELECT current_timestamp AS LAST_TIME
        FROM   DUAL
    </select>
</mapper>
 

Shobit Beltangdy

unread,
Jun 2, 2015, 3:03:19 AM6/2/15
to mybati...@googlegroups.com
Thanks Ikchan. However, this still does not answer OP's (and my) question.  What we were wondering is whether it is possible to achieve this without using a resultMap.

Just like how you can write a select like
<select id='someId' resultType='java.lang.String'> .... </select>

how can we implicitly do something like
<select id='someId' resultType='org.joda.time.DateTime'>...</select>

where we have a custom DateTimeTypeHandler having an annotation @JavaType=DateTime.class?

Is that possible, or is resultMap the only way to achieve this?

Ikchan Sim

unread,
Jun 2, 2015, 3:40:57 AM6/2/15
to mybati...@googlegroups.com
Use the DateTypeHandler class jdbcType = "java.sql.Timestamp" type is implicitly bound to javaType = "java.util.Date".
If you want to use your Custom TypeHandler, you should use an explicit <resultMap />



@MappedTypes(value = 
DateTime.class)
@MappedJdbcTypes(value = { JdbcType.TIMESTAMP})
public class CustomTypeHandler extends BaseTypeHandler<byte[]> {
    // do something...
}

Ikchan Sim

unread,
Jun 2, 2015, 3:51:35 AM6/2/15
to mybati...@googlegroups.com
Do not you look at the ResultSetHandler class it will help.
ResultTypeHandler.png
Reply all
Reply to author
Forward
0 new messages