-->

How to properly use Scala Play Anorm and Option[St

2019-05-11 04:54发布

问题:

What is the proper way to insert Option[String] when it is None? The below code inserts an empty string, which is not the same as NULL in mysql.

Is the only way to build the SQL string beforehand based on the content of partnerCode? Sigh...Anorm...

DB.withConnection { implicit connection =>

  val id: Option[Long] = SQL(
    """
    INSERT INTO users (email, partner_code, is_active, created, pass) VALUES ({email}, {partnerCode}, 0, NOW(), {pass})
    """
  ).on(
    'email -> user.email,
    'partnerCode -> user.partnerCode.getOrElse(""),  // FIXME: how to use NULL keyword instead of empty string? Is Anorm just this dumb?
    'pass -> hashPassword(user.password.get)
  ).executeInsert()

  id.get

}

回答1:

None should actually work fine if you import anorm._ or anorm.toParameterValue:

'partnerCode -> user.partnerCode