Search code examples
scalaplayframeworkplayframework-2.0anorm

Run-time Error while using anorm in scala


I have tried to load some data from database using anorm. But I got following runtime error

java.lang.RuntimeException: ColumnName(locations.Ref,Some(Ref))

Here is my Model class

package models
import play.api.db._
import play.api.Play.current

import anorm._
import anorm.SqlParser._

import scala.language.postfixOps
import scala.collection.mutable.ListBuffer

    case class Location(id: Int, name: String,ref:String,isactive:Int)


        object Location {

            /**
            * Parse a Location from a ResultSet
            */
            val loc = {
                get[Int]("Locations.Id") ~
                get[String]("Locations.Name")~
                get[String]("Locations.Ref")~
                get[Int]("Locations.Active") map {
                case id~name~ref~isactive => Location(id, name,ref,isactive)
                }
            }


             //Get All Locations from DB
              def findAllLocations():List[Location] = DB.withConnection { implicit c =>
                   SQL("SELECT Id,Name,Ref,Active from Locations").as(Location.loc *)
              }


}

Here is my table

enter image description here


Solution

  • I found the solution

    I have changed the code as follows replace get[String]("Locations.Ref") for get[Option[String]]("Locations.Ref")

    val loc = {
       get[Int]("Locations.Id") ~
       get[String]("Locations.Name")~
       get[Option[String]]("Locations.Ref")~
       get[Int]("Locations.Active") map {
       case id~name~ref~isactive => Location(id, name,ref,isactive)
       }
    }
    

    And also change the case class as ref:String to ref:Option[String]

     case class Location(id: Int, name: String,ref:Option[String],isactive:Int)