在MyBatis中使用基于resultType的隐式TypeHandler进行选择

Cho*_*hop 12 java jodatime mybatis

我试图在MyBatis中选择一个时间戳并将其作为LocalDateTime(来自joda-time)返回.

如果我尝试将结果作为a返回,我的配置工作正常java.sql.Timestamp.我证明我的类型处理程序工作正常:如果我LocalDateTime在MyBatis映射器文件中使用包含as only字段和resultMap 的包装类,我会得到正确的结果.

但是,当我尝试为这个select 指定org.joda.time.LocalDateTimeas时resultType,我总是得到null,好像忽略了类型处理程序.

据我所知,在我拥有的情况下,MyBatis使用默认的typeHandler resultType="java.sql.Timestamp".因此,我希望它使用我在会议时配置的typeHandler之一resultType="org.joda.time.LocalDateTime".

我错过了什么?有没有办法使用我的typeHandler或者我被迫创建一个包装类和resultMap?这是我的后备解决方案,但我想尽可能避免它.

任何帮助赞赏.谢谢.

MyBatis的-config.xml中

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeHandlers>
        <typeHandler javaType="org.joda.time.LocalDate" jdbcType="DATE" handler="...LocalDateTypeHandler"/>
        <typeHandler javaType="org.joda.time.LocalDateTime" jdbcType="TIMESTAMP" handler="...LocalDateTimeTypeHandler"/>
    </typeHandlers>
</configuration>
Run Code Online (Sandbox Code Playgroud)

NotifMailDao.java

import org.joda.time.LocalDateTime;

public interface NotifMailDao {

    LocalDateTime getLastNotifTime(String userId);
}
Run Code Online (Sandbox Code Playgroud)

NotifMailDao.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="lu.bgl.notif.mail.dao.NotifMailDao">

    <select id="getLastNotifTime" resultType="org.joda.time.LocalDateTime">
        SELECT current_timestamp
        AS last_time
        FROM DUAL
    </select>
</mapper>
Run Code Online (Sandbox Code Playgroud)

Cho*_*hop 6

要使用 TypeHandler 配置,MyBatis 需要知道结果对象的 Java 类型和源列的 SQL 类型。

这里我们使用 a resultType<select />所以 MyBatis 知道 Java 类型,但是如果我们不设置它就无法知道 SQL 类型。唯一的方法是使用<resultMap />.

解决方案

您需要使用包含要返回的对象的单个字段创建一个 Bean(让我们称之为该字段time)并使用一个<resultMap />

<select id="getLastNotifTime" resultMap="notifMailResultMap">
Run Code Online (Sandbox Code Playgroud)
<resultMap id="mapLastTime" type="MyWrapperBean">
    <result property="time" column="my_sql_timestamp" javaType="org.joda.time.LocalDateTime"
        jdbcType="TIMESTAMP" />
</resultMap>
Run Code Online (Sandbox Code Playgroud)

如果您不想创建专用 bean,您也可以按照Shobit 的建议type=hashmap在您的设备上使用该属性。<resultMap />

变体:设置属性 LocalDateTime

Google Groups 上提出了一个解决方案,直接设置LocalDateTime.

我对它的理解(如果我错了请评论)是它设置了LocalDateTime. 我不会保证它,因为我在API 文档中没有找到相应的内容(我还没有测试过),但如果你认为它更好,请随时使用它。

<resultMap id="mapLastTime" type="org.joda.time.LocalDateTime">
    <result property="lastTime" column="my_sql_timestamp" javaType="org.joda.time.LocalDateTime"
        jdbcType="TIMESTAMP" />
</resultMap>
Run Code Online (Sandbox Code Playgroud)

为什么它与 java.sql.Timestamp

Timestamp是 SQL 的标准 Java 类型,具有默认的 JDBC 实现 ( ResultSet.getTimestamp(int/String))。MyBatis 的默认处理程序使用这个 getter 1,因此不需要任何 TypeHandler 映射。我希望每次使用默认处理程序之一时都会发生这种情况。


1:这是一种预感。需要引用!

这个答案只等着被更好的东西取代。请贡献!