问题
I have a postgres table -
CREATE TABLE "Contest"
(
id serial NOT NULL,
name varchar(100) NOT NULL,
type char(1) NOT NULL,
status char(1) NOT NULL,
...
)
I'm trying to get field values type
and status
back to my Play 2.x (Anorm) application:
val parseContest = {
get[Pk[Int]]("id") ~
get[String]("name") ~
get[Char]("type") ~
get[Char]("status") map {
case id~name~c_type~status =>
Contest(id, name, c_type, status)
}
}
and get error:
could not find implicit value for parameter extractor: anorm.Column[Char]
Looks like 'Char' is not supported by anorm.
What should I change in my code? Is it good practice to use get[String]("status")
and then status.head
as workaround?
回答1:
I think you could write an implicit converter for your char
columns. That would look like this:
implicit def columnToChar: Column[Char] = {
Column[Char](transformer = {
(value, meta) =>
val MetaDataItem(qualified, nullable, clazz) = meta
value match {
case ch: String => Right(ch.head)
case _ => Left(TypeDoesNotMatch("Cannot convert " + value + " to Char for column " + qualified))
}
})
}
Then be sure this converter is in scope.
I'm not sure the value would be a String but you can check it and make the corresponding corrections.
回答2:
There is recently merged PR on Anorm about that: https://github.com/playframework/playframework/pull/2189
来源:https://stackoverflow.com/questions/20024357/how-to-get-char-values-from-postgres-with-anorm