Anorm 2.3 multi-value parameter: required anorm.NamedParameter

时光怂恿深爱的人放手 提交于 2019-12-08 05:48:31

问题


Using scala 2.11.1 on play framework 2.3.

Because Anorm didn't support multi-value parameters in previous versions I used David's workaround. Anorm now supports multi-value parameters and I started removing the workaround and using Anorm multi-value parameters.

The example [sic] mentioned:

// With default formatting (", " as separator)
SQL("SELECT * FROM Test WHERE cat IN ({categories})").
  on('categories -> Seq("a", "b", "c")
// -> SELECT * FROM Test WHERE cat IN ('a', 'b', 'c')

Yet my code:

val names = List("Able", "Baker", "Charlie") // Passed as a parameter to my method!
val result =
  SQL( """
    SELECT city
    FROM addresses
    WHERE name IN ({names});
  """ ).on( 'names -> names ).as( scalar[String] * )

gives me this error:

type mismatch;
 found   : (Symbol, List[String])
 required: anorm.NamedParameter

or

type mismatch;
 found   : (Symbol, scala.collection.immutable.Seq[String])
 required: anorm.NamedParameter

depending if i try a list or sequence (or one of the suggestions to map it).

I'm no expert, by far, and I think it's missing some implicit conversion? Clueless to find out how/what/where. Tips/suggestions/solutions welcome!


回答1:


Looking at Anorm document, you will see there is no multi-value example using List. Indeed that's on purpose as instance of NamedParameter is implemented only for Seq[T].

Just updating your code to val names = Seq("Able", "Baker", "Charlie") make it valid (and compiles).

I would suggest to edit your code using Anorm interpolation:

val result = 
  SQL"SELECT city FROM addresses WHERE name IN ($names)" as scalar[String].*

// OR (if names won't change):
val result = SQL"""SELECT city FROM addresses
    WHERE name IN (${Seq("Able", "Baker", "Charlie")})""".
  as(scalar[String].*)

EDIT: See changes in Anorm https://github.com/playframework/playframework/pull/3257 (supports List)



来源:https://stackoverflow.com/questions/25140720/anorm-2-3-multi-value-parameter-required-anorm-namedparameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!