ope*_*sas 6 parsing anorm playframework-2.0
我一直在看计算机数据库示例,我注意到为了重用计算机解析器,list方法使用Computer.withCompany解析器,它返回一个元组(计算机,公司)
在我必须处理的情况下,而不是对计算机的id的引用,我希望有一个Computer对象,就像这样
case class Computer(id:Pk [Long] = NotAssigned,name:String,introduction:Option [Date],停止:Option [Date],company:Company)
所以我在想如何实现以下内容(当然是seudocode)
val simple = {
get[Pk[Long]]("computer.id") ~
get[String]("computer.name") ~
get[Option[Date]]("computer.introduced") ~
get[Option[Date]]("computer.discontinued") ~
get[Company]("company.*") map {
case id~name~introduced~discontinued~company => Computer(id, name, introduced, discontinued, company)
}
}
Run Code Online (Sandbox Code Playgroud)
显然,棘手的部分是如何解决getCompany
任何的想法???
我有一个Idea实体和一个IdeaType实体(就像计算机和公司一样,在计算机数据库示例中)
case class IdeaTest(
val id: Pk[Long] = NotAssigned,
val name: String = "unknown idea",
val description: String = "no description",
val kind: IdeaType = IdeaType()
)
case class IdeaType (
val id: Pk[Long] = NotAssigned,
val name: String = "unknown idea type",
val description: String = "no description"
)
Run Code Online (Sandbox Code Playgroud)
我定义了一个TypeParser
val typeParser: RowParser[IdeaType] = {
get[Pk[Long]]("idea_type.id") ~
get[String]("idea_type.name") ~
get[String]("idea_type.description") map {
case id~name~description => IdeaType(
id, name, description
)
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试的第一件事是:
val ideaParser: RowParser[IdeaTest] = {
get[Pk[Long]]("idea.id") ~
get[String]("idea.name") ~
get[String]("idea.description") ~
typeParser map {
case id~name~description~ideaType => IdeaTest(
id, name, description, ideaType
)
}
}
Run Code Online (Sandbox Code Playgroud)
即使它编译正常,它仍然无法加载ideaType.
最后,我不得不定义一个没有ideaType的ideaParser,并使用typeParser进行组合:
val typeParser: RowParser[IdeaType] = {
get[Pk[Long]]("idea_type.id") ~
get[String]("idea_type.name") ~
get[String]("idea_type.description") map {
case id~name~description => IdeaType(
id, name, description
)
}
}
val ideaWithTypeParser = ideaParser ~ typeParser map {
case idea~kind => (idea.copy(kind=kind))
}
Run Code Online (Sandbox Code Playgroud)
这是使用它的代码:
def ideaById(id: Long): Option[IdeaTest] = {
DB.withConnection { implicit connection =>
SQL("""
select * from
idea inner join idea_type
on idea.idea_type_id = idea_type.id
where idea.id = {id}""").
on('id -> id).
as(ideaParser.singleOpt)
}
}
Run Code Online (Sandbox Code Playgroud)
我看到的唯一麻烦是,我必须以不一致的状态创建IdeaTest对象(没有ideaType),然后将其复制到具有正确IdeaType的另一个实例.