2012-01-11 61 views
4

我使用MyBatis和Spring集成,如here所述。在MyBatis/Spring中使用自定义类型

我进一步使用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的代码检查,但没有找到我的处理程序有....

回答

4

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

现在,上面的代码片段中的最后一行显式注册了一个处理程序null JdbcType。不幸的是,在@MappedJdbcTypes注释中包含null似乎是不可能的。这对我来说看起来像一个bug。

哦,你也许可以完全删除@MappedJdbcTypes注解,以使其工作。

UPDATE:

以下是我在我的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的日志记录级别调试看看它试图添加哪些。

我的类型处理器开始是这样的:

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

你的意思是,我们可以删除置于类型处理器的注释,并删除它执行处理程序的手动注册代码?然后也许它可以工作? ...我刚刚测试过这个场景,并且失败 – Sudarshan 2012-01-27 09:40:22

+0

是的,这就是我在自己的最新MyBatis发行版中为自己的选择和更新而工作的方式。所以唯一的注释是@MappedTypes(DateTime.class)。 – usethe4ce 2012-01-27 18:18:48

+0

你能告诉我哪个版本?如果你使用Spring与MyBatis集成? – Sudarshan 2012-01-28 07:41:28

相关问题