如何在scala使用playframework 2.0中的anorm解析器
问题描述:
我一直在看看computer-database sample,我注意到为了重用计算机解析器,list方法使用Computer.withCompany解析器,它返回一个元组(电脑,公司)如何在scala使用playframework 2.0中的anorm解析器
在我处理的情况下,而不是一提到我想有一个计算机对象的计算机的ID,这样
案例类计算机(ID:PK [长] = NotAssigned,名称:字符串,介绍:选项[日期],终止:选项[日期],公司:公司)
所以我觉得我荷兰国际集团如何实现类似下面的(它的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)
}
}
显然,棘手的问题将是如何解决getCompany
任何想法???
答
我有一个想法实体和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"
)
我定义了一个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 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
)
}
}
即使它编译好,它总是有问题加载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))
}
,这是用它的代码:唯一的麻烦我
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)
}
}
请参阅,是否必须以不一致的状态创建IdeaTest对象(不含ideaType),然后使用正确的IdeaType将其复制到另一个实例。
这个答案非常有用,有助于巩固我对编写解析器的理解,谢谢! – EdgeCaseBerg