Last active
December 18, 2015 10:49
-
-
Save mather/5771655 to your computer and use it in GitHub Desktop.
SlickでTimestampのカラムをDateTimeとして扱うために、暗黙の変換(implicit conversion)を行う方法。
単なるメモなので、動作は保証出来ません。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* util パッケージで宣言する場合 */ | |
package object util { | |
import java.sql.Timestamp | |
import com.github.nscala_time.time.Imports.DateTime | |
import scala.slick.lifted.MappedTypeMapper | |
/* 結果値 Timestamp をアプリケーションでは DateTime に変換して使う */ | |
implicit def dateTimeMapper = MappedTypeMapper.base[DateTime,Timestamp]( | |
/* f: DateTime -> Timestamp */ | |
dt => new Timestamp(dt.getMillis), | |
/* g: Timestamp -> DateTime */ | |
t => new DateTime(t.getTime) | |
) | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.github.nscala_time.time.Imports.DateTime | |
import scala.slick.driver.PostgresDriver.simple._ | |
import util._ | |
/* Todoデータクラス */ | |
case class Todo(id: Int, subject: String, createdAt: DateTime) | |
/* TodoテーブルのSlickによる定義 */ | |
object Todos extends Table[Todo]("todo"){ | |
def id = column[Int]("id", O.PrimaryKey, O.AutoInc) | |
def subject = column[String]("subject") | |
def createdAt = column[DateTime]("created_at", O.Default(DateTime.now)) | |
/* レコード自体をオブジェクトに変換するメソッド */ | |
def * = id ~ subject ~ createdAt <> (Todo.apply _, Todo.unapply _) | |
/* subjectを受け取ってIDと登録日を含めた挿入済みオブジェクトを返す(insert用) */ | |
def ins = subject returning * | |
} | |
/* テーブル作成 */ | |
db withSession { implicit session: Session => | |
Todos.ddl.create | |
} | |
/* INSERT */ | |
db withSession { implicit session: Session => | |
/* 挿入してTodoを受け取る */ | |
val todo = Todos.ins.insert("Some task.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment