Jun 5, 2015

Mybatis support for Java 8 time (JSR 310)

Mybatis is pretty cool library for mapping your database queries. Unfortunately it does not know anything about Java8 time API (JSR 310). Thus you can not yous in your POJO new date/time types like LocalDate, LocalDateTime, ZonedDate, ZonedDateTime etc.

You can solve this problem by creating your own mapper for mybatis, or you can use mappers I have created.

My mapper implementation provides next handlers for core java.time.* types:
  • java.time.Instant (via java.sql.Timestamp)
  • java.time.LocalDate (via java.sql.Date)
  • java.time.LocalDateTime (via java.sql.Timestamp)
  • java.time.LocalTime (via java.sql.Time)
  • java.time.OffsetDateTime (via java.sql.Timestamp)
  • java.time.ZonedDateTime (via java.sql.Timestamp)
You can get sources here: https://github.com/jneat/mybatis-java-time
Also you can use it as maven artifact.

Adding to your project

Note that latest version and instructions can be available in git repository.

Gradle

repositories {
  maven {
    url "https://jitpack.io"
  }
}

dependencies {
  compile 'com.github.jneat:mybatis-java-time:0.1'
}

Maven

<repository>
  <id>jitpack.io</id>
  <url>https://jitpack.io</url>
</repository>

<dependency>
  <groupId>com.github.jneat</groupId>
  <artifactId>mybatis-java-time</artifactId>
  <version>0.1</version>
</dependency>

Project configuration

Using mybatis configuration

Preferred way is to add package search option
<!-- in mybatis-config.xml add -->
<typeHandlers>
  <package name="com.github.jneat.mybatis"/>
</typeHandlers>
Also you can directly point at each handler
<!-- in mybatis-config.xml add -->
<typeHandlers>
  <typeHandler handler="com.github.jneat.mybatis.InstantHandler"/>
  <typeHandler handler="com.github.jneat.mybatis.LocalDateHandler"/>
  <typeHandler handler="com.github.jneat.mybatis.LocalDateTimeHandler"/>
  <typeHandler handler="com.github.jneat.mybatis.LocalTimeHandler"/>
  <typeHandler handler="com.github.jneat.mybatis.OffsetDateTimeHandler"/>
  <typeHandler handler="com.github.jneat.mybatis.ZonedDateTimeHandler"/>
</typeHandlers>

Using mybatis with spring

I will not describe how to configure mybatis with spring, only will show my part.
<bean id="yourBeanId" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- your bean configuration goes here -->
    <property name="typeHandlersPackage" value="com.github.jneat.mybatis" />
</bean>

Now you will be able to use Java8 time API in your domain objects. No additional configuration requires.