squeryl date to long conversion

2019-08-30 08:57发布

问题:

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