【发布时间】:2014-09-27 05:53:46
【问题描述】:
在将 Play 框架与 Slick 一起使用时,从固定字符数据库列中修剪值的正确方法是什么,正确的位置在哪里?
我要修剪字符串的原因是数据库架构指定了character(40) 列类型而不是character varying 类型。
我有这个案例类:
case class Test(id: Long, trimMe: Option[String])
我有这个 Slick 表关系:
class Tests(tag: Tag) extends Table[Test](tag, "test") {
def id = column[Long ]("test_id", O.PrimaryKey, O.AutoInc)
def trimMe = column[String]("trim_me" )
def * = (id, trimMe) <> (Test.tupled, Test.unapply _)
}
我有这个带有 JSON 映射的测试类:
object TrimTest {
implicit val testWrite = new Writes[Test] {
def writes(test: Test) = Json.obj(
"id" -> test.id ,
"trim" -> test.trimMe
)}
}
这一切都有效,但返回一个空格填充的字符串。
我在 JSON 映射器中尝试了一些修剪的变体:
object TrimTest {
implicit val testWrite = new Writes[Test] {
def writes(test: Test) = Json.obj(
"id" -> test.id ,
"trim1" -> test.trimMe.map(_.trim) ,
"trim2" -> test.trimMe.fold("") {_.trim} ,
"trim3" -> test.trimMe.map(_.trim).getOrElse("")
)}
}
上面的trim1 有效,但是当可选值不存在时返回null。
trim2 确实适用于所有情况,但我看到它在各个地方都说map 然后getForElse 比使用fold 是“更惯用的Scala”。
trim3 刚刚超出了我目前对 Scala 的理解的极限,显示了我的意图但无法编译。
trim3情况下的编译错误为:
类型不匹配; 发现:对象 必需:play.api.libs.json.Json.JsValueWrapper
我当然可以忍受使用fold,但是通常的方法是什么?
【问题讨论】:
标签: scala playframework-2.0 slick-2.0