首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在MyBatis/Spring中使用自定义类型

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

Stack Overflow用户
提问于 2012-01-11 16:02:07
回答 1查看 16.2K关注 0票数 4

我正在使用here中描述的Spring Integration的MyBatis。

我进一步使用了Joda Date API,而不是Java Date API,现在的棘手之处在于确保MyBatis能够识别Joda Date API,并使我能够对其进行查询。

现在,记录在案的实现此功能的方法是使用DateTypeHandler

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

所以我的班级看起来像

代码语言:javascript
复制
@MappedTypes(value = DateTime.class)
@MappedJdbcTypes(value = {JdbcType.DATE,JdbcType.TIME,JdbcType.TIMESTAMP})

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

这不能注册我的自定义类型处理程序...,我必须做的是在应用程序启动时编写这样的代码……

代码语言:javascript
复制
 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代码中进行了检查,但在那里找不到我的处理程序……

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-01-27 08:01:46

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

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

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

更新:

下面是我在applicationContext.xml中的设置:

代码语言:javascript
复制
<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是这样开始的:

代码语言:javascript
复制
@MappedTypes(DateTime.class)
public class DateTimeTypeHandler implements TypeHandler<DateTime> {...}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8815983

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档