MyBatis/Springでカスタムタイプを使用します
質問
説明されているように、私は春の統合でmybatisを使用しています ここ.
さらに、Java Date APIの代わりにJoda 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コードで検査を行ってハンドラーを見つけることができなかったため、私のタイプは(注釈だけを使用して)登録されていないと確信しています。
解決
また、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ロギングレベルを設定してデバッグして、追加しようとするものを確認できます。
私のタイプハンドラーは次のように始まります:
@MappedTypes(DateTime.class)
public class DateTimeTypeHandler implements TypeHandler<DateTime> {...}