简体   繁体   中英

How to map a query result to case class using Anorm in scala

I have 2 case classes like this :

case class ClassTeacherWrapper(
                          success: Boolean,
                          classes: List[ClassTeacher]
                        )

2nd one :

case class ClassTeacher(
                      clid: String,
                      name: String
                    )

And a query like this :

  val query =
    SQL"""
      SELECT
        s.section_sk::text AS clid,
         s.name AS name
         from
       ********************
    """

PS I put * in place of query for security reasons :

So my query is returning 2 values. How do i map it to case class ClassTeacher

currently I am doing something like this :

def getClassTeachersByInstructor(instructor: String, section: String): ClassTeacherWrapper = {

implicit var conn: Connection = null
try {

  conn = datamartDatasourceConnectionPool.getDBConnection()
  // Define query
  val query =
    SQL"""
      SELECT
        s.section_sk::text AS clid,
         s.name AS name
       ********
    """



  logger.info("Read from DB: " + query)


  // create a List containing all the datasets from the resultset and return
  new ClassTeacherWrapper(
       success =true,
      query.as(Macro.namedParser[ClassTeacher].*)

  )
  //Trying new approch
  //val users = query.map(user => new ClassTeacherWrapper(true, user[Int]("clid"), user[String]("name")).tolist
}
catch {
  case NonFatal(e) =>
    logger.error("getGradebookScores: error getting/parsing data from DB", e)
    throw e
  }
}

with is I am getting this exception :

{
   "error": "ERROR: operator does not exist: uuid = character varying\n  
    Hint: No operator matches the given name and argument type(s). You 
    might need to add explicit type casts.\n  Position: 324"
 }

Can anyone help where am I going wrong. I am new to scala and Anorm What should I modify in query.as part of code

Do you need the success field? Often an empty list would suffice?

I find parsers very useful (and reusable), so something like the following in the ClassTeacher singleton (or similar location):

val fields = "s.section_sk::text AS clid, s.name"

val classTeacherP =
  get[Int]("clid") ~
  get[String]("name") map {
    case clid ~ name =>
    ClassTeacher(clid,name)
  }

def allForInstructorSection(instructor: String, section: String):List[ClassTeacher] = 
  DB.withConnection { implicit c => //-- or injected db
    SQL(s"""select $fields from ******""")
      .on('instructor -> instructor, 'section -> section)
      .as(classTeacherP *)
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM