简体   繁体   中英

Is it possible to get XMLGregorianCalendar directly from MyBATIS?

I work with public StackOverflow dump and have everything stored in MySQL. Now, I want to perform some analyses using Java and MyBATIS. For some of these I need to extract timeseries for a user, or a particular question etc. So for this, lets say posts and their timestamps, I have a MyBatis query:

 <select id="GetAllPostsTimeStamps" resultType="java.util.Date">
     SELECT creationDate from posts
 </select>

which hands the timestamp data to MyBatis ResultHandler, where I do this transformation:

@Override
public void handleResult(ResultContext context) {
   TimeZone tz = TimeZone.getTimeZone("UTC");
   TimeZone.setDefault(tz);
   Date tstamp = (Date) context.getResultObject();
   XMLGregorianCalendar xmlTstam = Tstamp.makeTimestamp(tstamp.getTime());
   ...etc...
}

I really need to use XMLGregorianCalendar because all my downstream logic relies on this type.

Is it possible to tell MyBatis with its handlers feature to make transformation of SQL datetime to XMLGregorianCalendar internally (ie I will code the handler only once), so I will get proper timestamps out of it everytime I need?

Editing to add more clarity.

So, when I save java objects with XMLGregorianCalendar fields into DB (MySQL datetime type) I use an implementation of MyBatis handler:

XMLGregorianCalendarDateTypeHandler implements TypeHandler<XMLGregorianCalendar>
...

which I specify in the INSERT query like this:

    ..., #{creationDate,
           javaType=javax.xml.datatype.XMLGregorianCalendar,
           jdbcType=TIMESTAMP,                
           typeHandler=...XMLGregorianCalendarTypeHandler},...

is there a way to specify the backward transform handler for SELECT type queries?

I found why it wasnt working, maybe it will help somebody:

So, when I configure a handler specifying both types: JDBC and Java, this doesnt work:

<typeHandler javaType="javax.xml.datatype.XMLGregorianCalendar" 
      jdbcType="TIMESTAMP"
      handler="my.package.XMLGregorianCalendarTimestampTypeHandler" />

But if I specify just Java type it works. Magic:

<typeHandler javaType="javax.xml.datatype.XMLGregorianCalendar" 
      handler="my.package.XMLGregorianCalendarTimestampTypeHandler" />

Not sure if it is a bug or a feature.

I don't know MyBatis, but will this help?

DatatypeFactory factory = DatatypeFactory.newInstance();
XMLGregorianCalendar calendar = factory.newXMLGregorianCalendar();
calendar.setMillisecond(tstamp.getTime());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM