squeryl date to long conversion

社会主义新天地 提交于 2019-12-12 02:28:03

问题


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!


回答1:


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...



来源:https://stackoverflow.com/questions/14407269/squeryl-date-to-long-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!