在MyBatis / Spring中使用自定义类型

时间:2012-01-11 08:02:07

标签: spring mybatis

我正在使用MyBatis和Spring here

我进一步使用Joda Date API而不是Java Date API,现在棘手的一点是确保MyBatis能够识别Joda Date API,并使我能够查询相同的内容。

现在记录的实现方法是使用DateTypeHandler

我假设如果我们使用正确的注释,Mybatis会选择自定义处理程序并将其注册到sqlsessionfactory。

所以我的班级看起来像

@MappedTypes(value = DateTime.class)
@MappedJdbcTypes(value = {JdbcType.DATE,JdbcType.TIME,JdbcType.TIMESTAMP})

public class MyBatisJodaDateTimeType extends DateTypeHandler {
......
.....
}

一些如何不注册我的自定义类型处理程序....,我要做的是,在应用程序启动时编写这样的代码......

 SqlSessionFactory mybatisSessionFactory = applicationContext.getBean("sqlSessionFactory", SqlSessionFactory.class);
        MyBatisJodaDateTimeType myBatisJodaDateTimeType = applicationContext.getBean("myBatisJodaDateTimeType", MyBatisJodaDateTimeType.class);

        mybatisSessionFactory.getConfiguration().getTypeHandlerRegistry().register(DateTime.class, myBatisJodaDateTimeType);
        mybatisSessionFactory.getConfiguration().getTypeHandlerRegistry().register(DateTime.class, JdbcType.DATE, myBatisJodaDateTimeType);
        mybatisSessionFactory.getConfiguration().getTypeHandlerRegistry().register(DateTime.class, JdbcType.TIME, myBatisJodaDateTimeType);
        mybatisSessionFactory.getConfiguration().getTypeHandlerRegistry().register(DateTime.class, JdbcType.TIMESTAMP, myBatisJodaDateTimeType);
        mybatisSessionFactory.getConfiguration().getTypeHandlerRegistry().register(DateTime.class, null, myBatisJodaDateTimeType);

我知道它看起来像垃圾,我想避免它,我无法让MyBatis扫描我的应用程序以获取这些注释,然后自动注册我的自定义类型处理程序?

我确信我的类型尚未注册(仅使用注释),因为我在MYBatis代码中进行了检查,但在那里找不到我的处理程序....

1 个答案:

答案 0 :(得分:4)

我遇到了同样的问题,也是为了Joda DateTime TypeHandler。跟踪,我看到处理程序 实际已注册。但是,TypeHandlerRegistry.getTypeHandler似乎使用null jdbcType来查找处理程序。

现在,上面代码片段中的最后一行显式注册了null JdbcType的处理程序。不幸的是,似乎无法在null注释中包含@MappedJdbcTypes。所以这看起来像是一个错误。

哦,您可以完全删除@MappedJdbcTypes注释,以使其正常工作。

更新:

以下是我在applicationContext.xml中设置的方法:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="mapperLocations" value="classpath*:META-INF/persistence/*.xml" />
    <property name="typeAliasesPackage" value="com.mycompany.data" />
    <property name="typeHandlersPackage" value="com.mycompany.typehandler" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.mycompany.persistence" />
</bean>

如果您通过扫描这样的包来选择类型处理程序,则可以将MyBatis日志记录级别设置为debug以查看它尝试添加哪些类型。

我的TypeHandler就是这样开始的:

@MappedTypes(DateTime.class)
public class DateTimeTypeHandler implements TypeHandler<DateTime> {...}