Joda Time/iBATIS集成类是否存在一个库? [英] Does a library exist with Joda Time / iBATIS integration classes?

查看:131
本文介绍了Joda Time/iBATIS集成类是否存在一个库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看来我必须为DateTime和LocalDateTime Joda类型都实现com.ibatis.sqlmap.client.extensions.TypeHandlerCallback.这没什么大不了的,但是如果它在其他地方实现,我宁愿只使用它.

解决方案

IMO没有干净,灵活的解决方案. Jodatime日期比JDBC本机类型(java.sql.Datejava.sql.Timestamp ...)更灵活,如果映射到它们,则可能会丢失信息(时区).一个完整"的实现(例如,使用字符串可能绕过getDate()/getTimestamp()等JDBC方法,例如使用字符串)将取决于您的JDBC驱动程序和数据库(实际上,没有数据库具有像Jodatime那样具有表现力的日期时间类型).

这是我为LocalDateTime做过的一个相当琐碎的实现.尚未经过充分测试,并且假设您的数据库时间戳记代表本地日期时间.

public Object getResult(ResultGetter getter) throws SQLException {
   Timestamp date = getter.getTimestamp();
   if(date == null) return null; 
   LocalDateTime ldt = null;
   try {
      ldt = LocalDateTime.fromDateFields(date);
   } catch(IllegalArgumentException e) {
      throw new SQLException("illegal value for a LocalDateTime : " + date);
   }
   return ldt; 
}

public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {
   java.sql.Timestamp date = null; 
   if(parameter != null) { 
      LocalDateTime ldt = (LocalDateTime) parameter;
      date = new Timestamp(ldt.toDateTime().getMillis());
   } 
   setter.setTimestamp(date);
}

It looks like I have to implement com.ibatis.sqlmap.client.extensions.TypeHandlerCallback for both DateTime and LocalDateTime Joda types. This isn't a big deal, but if it's implemented somewhere else I'd rather just use that.

解决方案

There are no clean and flexible solutions, IMO. Jodatime dates are more flexible than the JDBC native types (java.sql.Date,java.sql.Timestamp...) and if you map to them you might be losing information (timezones). An "full" implementation, (perhaps bypassing the getDate()/getTimestamp() etc JDBC methods, using strings for example) would depend on your JDBC driver and database (and practically no database has datetime type as expressive as Jodatime's).

Here's a rather trivial implementation I did once for LocalDateTime. Not very tested, and it assumes your DB timestamps represent local datetimes.

public Object getResult(ResultGetter getter) throws SQLException {
   Timestamp date = getter.getTimestamp();
   if(date == null) return null; 
   LocalDateTime ldt = null;
   try {
      ldt = LocalDateTime.fromDateFields(date);
   } catch(IllegalArgumentException e) {
      throw new SQLException("illegal value for a LocalDateTime : " + date);
   }
   return ldt; 
}

public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {
   java.sql.Timestamp date = null; 
   if(parameter != null) { 
      LocalDateTime ldt = (LocalDateTime) parameter;
      date = new Timestamp(ldt.toDateTime().getMillis());
   } 
   setter.setTimestamp(date);
}

这篇关于Joda Time/iBATIS集成类是否存在一个库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆