scalaanorm

Anorm - generic insert


Is there a way to use Anorm like a regular ORM? I'd like to have a method that just inserts an element provided.

  def insert[T](element: T)(implicit connection: Connection) = {
    element.insert(connection)
  }

I can definitely implement it by myself, but feels like I'm re-implementing an ORM... Old anorm version had this Magic[T] but I can't see it now


Solution

  • The documentation clearly states that Anorm is not an ORM (and will never be).

    As indicated, to insert or update a T value, an instance of the ToStatement typeclass must be provided.

    Some macros are provided to automatically materialize such instance.

    import anorm.{ Macro, SQL, ToParameterList }
    import anorm.NamedParameter
    
    case class Bar(v: Int)
    
    val bar1 = Bar(1)
    
    // Convert all supported properties as parameters
    val toParams1: ToParameterList[Bar] = Macro.toParameters[Bar]
    
    val params1: List[NamedParameter] = toParams1(bar1)
    // --> List(NamedParameter(v,ParameterValue(1)))
    
    val names1: List[String] = params1.map(_.name)
    // --> List(v)
    
    val placeholders = names1.map { n => s"{$n}" } mkString ", "
    // --> "{v}"
    
    val generatedStmt = s"""INSERT INTO bar(${names1 mkString ", "}) VALUES ($placeholders)"""
    val generatedSql1 = SQL(generatedStmt).on(params1: _*)