使用anorm创建动态SQL

时间:2014-10-13 14:15:36

标签: scala playframework playframework-2.0 anorm

我不想删除并重新插入每一行,所以我使用以下内容尝试使用带有anorm的多行:

SQL("""
            delete from PERSON_ROLES 
            WHERE person_id = {userId}
            and role_id not in ({rolescommastring})
            )
            """).on('userId -> userId,
                    'rolescommastring -> rolescommastring).execute()

上面会产生一个它不喜欢的字符串,我得到:

  

c.j.b.PreparedStatementHandle - delete from PERSON_ROLES WHERE person_id = 1460 and role_id not in ( '1, 3, 8, 9' )

我可以使用anorm创建动态sql吗?

2 个答案:

答案 0 :(得分:4)

自Anorm 2.3以来,支持多值参数。

SQL("""
        delete from PERSON_ROLES 
        WHERE person_id = {userId}
        and   role_id not in ({rolescommastring})
        )
        """).on('userId -> userId,
                'rolescommastring -> Seq("id1", "id2", "id3")).execute()

https://www.playframework.com/documentation/2.3.x/ScalaAnorm

有更多类似的例子

答案 1 :(得分:0)

Anorm并不支持' IN'条款。大多数ORM(如scala-slick)都是一样的,因为预处理语句不支持IN子句

我使用的流程来自https://groups.google.com/forum/#!topic/play-framework/qls6dhhdayc/discussion

基本上这样的事情应该有效

val params = List(1, 3, 8, 9) 
val paramsList = for ( i <- 0 until params.size ) yield ("role_id" + i)

SQL("""
        delete from PERSON_ROLES 
        WHERE person_id = {userId}
        and   role_id not in ({%s})
        )
        """.format(paramsList.mkString("},{"))).on('userId -> userId ++ 
                paramsList.zip(params)).execute()