长时间转换 [英] squeryl date to long conversion

查看:147
本文介绍了长时间转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Squeryl将java.util.Date(或Timestamp)作为int(或Long)存储在我的数据库中。



我想控制如何将日期转换为数字,反之亦然。



如何实现?



来自java / hibernate的scala / squeryl相当新鲜。
回到java / hibernate我可以创建用户类型,并注册它们全局,或者在具有注释的字段上使用它们localy。这个用户类型定义了如何将对象类型保留到db的方法,以及如何从db中加载它。



我读了一些squeryl和scala文档,注意到两个东西:


  1. 有自定义类型


  2. 是一个调用转换的隐式函数机制


我知道其中一个可以帮助我,但是我没有找到任何好的完整的例子来了解如何。



任何帮助不胜感激!

解决方案

请看这个例子:



https:// github。 com / max-l / squeryl-extended-field-types-example / blob / master / src / main / scala / example / MyCustomTypes.scala



在您的情况下,您为TLong(支持JDBC类型)和DateTime for Date(您可能需要考虑使用joda日期),将TTimestamp分配。

 code> implicit val dateAsLongTEF = new NonPrimitiveJdbcMapper [Long,Date,TLong](longTEF,this){
def convertFromJdbc(v:Long)= new Date(v)
def convertToJdbc(v:日期)= v.getTime
}

隐式val optionDateAsLongTEF =
new TypedExpressionFactory [Option [Date],TOptionLong]
with DeOptionizer [Long,Date,选项[日期],TOptionLong] {

val deOptionizer = dateAsLongTEF
}
比较数字列与DSL中的长支持列。



更新:有一个限制,阻止重新注册一个原始类型
,所以你需要一个包装器类型,我更新了github项目...


I want to store java.util.Date (or Timestamp) as an int (or Long) in my db using Squeryl.

I'd like to control how the date is transformed to the number and vice versa.

How can I achieve this?

I'm pretty new to scala/squeryl, coming from java/hibernate. Back in java/hibernate I could create user types and either register them globaly or use them localy on a field with an annotation. This user type defined methods for how to persist the object type to db and how to load it from the db.

I read some of the squeryl and scala docs, noticed two things:

  1. there are custom types

  2. there is a implicit function mechanism that is called for conversions

I know one of these can help me but I didn't find any good full examples to understand how.

Any help is appreciated!

解决方案

Please see this example :

https://github.com/max-l/squeryl-extended-field-types-example/blob/master/src/main/scala/example/MyCustomTypes.scala

in your case, you subsitute TTimestamp for TLong (the backing JDBC type) and DateTime for Date (you might want consider using the joda date though).

implicit val dateAsLongTEF = new NonPrimitiveJdbcMapper[Long, Date, TLong](longTEF, this) {
  def convertFromJdbc(v: Long) = new Date(v)
  def convertToJdbc(v: Date) = v.getTime
}

implicit val optionDateAsLongTEF = 
new TypedExpressionFactory[Option[Date], TOptionLong] 
  with DeOptionizer[Long, Date, TLong, Option[Date], TOptionLong]  {

    val deOptionizer = dateAsLongTEF
}

Note: the fact that you use TLong and TOptionLong means that you'll be able to compare a number column to a long backed column in the DSL.

Update: there is a limitation that prevents re registering a primitive type, so you'll need to have a wrapper type, I updated the example in the github project...

这篇关于长时间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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