Scrooge McD Scrooge McD - 1 month ago 29
Java Question

Java 8 LocalDate mapping with mybatis

I am using java.time.LocalDate (Java 8) to represent some of the member fields in a Java class.

class Test{
private LocalDate startDate;
private LocalDate endDate;
//other fields

//getters and setters
}


I am also using mybatis, to interact with my database.
On retrieving some data from the DB, all other fields get populated properly,
but the startDate and endDate fields end up as null.

If ,however, I use java.util.Date, as in,

private Date startDate;
private Date endDate;


I get the proper values retrieved in these two fields (startDate and endDate) when I declare them as java.util.Date.

Is it because mybatis does not currently have a mappping of 'Timestamp'(SQL Server) to java.time ?

How should I go about using java.time.LocalDate to map with MyBatis ?

Answer

Please, look here: http://mybatis.github.io/mybatis-3/configuration.html#typeHandlers

To use LocalDate and Timestamp you have to write a custom typeHandler, like this:

// ExampleTypeHandler.java
@MappedTypes(LocalDate.class)
public class LocalDateTypeHandler extends BaseTypeHandler<LocalDate> {

  //implement all methods
}

config your config.xml like this:

<!-- mybatis-config.xml -->
<typeHandlers>
  <typeHandler handler="your.package.LocalDateTypeHandler"/>
</typeHandlers>

It should help.

Comments