Anibal
Anibal

Reputation: 31

could not find implicit value for parameter connection: java.sql.Connection

I am starting with Scala. I have my method in the model:

def get_courses = {

    DB.withConnection { implicit connection =>

      val result = SQL("SELECT * FROM courses")
      result

    }

When I call it from Controllers I am doing this (I want to get a List):

val AllCourses = CourseModel.get_courses

// Transform the resulting Stream[Row] as a List[(String)]
val CoursesList = AllCourses().map(row =>
  row[String]("name")
).toList

When I am trying to transform the stream[Row] in a List (from https://www.playframework.com/documentation/2.0/ScalaAnorm) I am getting error

could not find implicit value for parameter connection: java.sql.Connection

related with AllCourses() code.

Any ideas?

However it is strange because when I add all the same method

def get_courses = DB.withConnection { implicit connection =>
   val result = SQL("SELECT * FROM courses")

   // Transform the resulting Stream[Row] as a List[(String)]
   val CoursesList = result().map(row =>
       row[String]("name")
   ).toList

} 

it works (as the https://www.playframework.com/documentation/2.0/ScalaAnorm example)

But I want to have them separated in Controllers...

Upvotes: 2

Views: 1733

Answers (1)

wwkudu
wwkudu

Reputation: 2796

I suspect the answer to your question is that the actual database connection does not get used when you simply define the sql statement. If you hover over the SQL call, you will see it does not require a DB connection. result(), or SQL("...")() however, does need a connection and this is where the actual call to the database will take place.

Can I humbly suggest that you write your controllers only to operate on your class objects, and not to interact with anorm/database-level artefacts. So for example, your model layer would have a method get_courses : List[Course] (or perhaps simply all because you will probably reference it as a method of the Course companion object, i.e. Course.all(), so using course in the method name is probably not necessary) which returns Course objects. Your controllers would call this as needed, and not need to worry whether the Course object is coming from a database, from a json file, or from anywhere.

I also find parsers very useful, so define a parser courseP for example, which creates Course objects and is then used wherever you need to read one or more Courses - with something like SQL("select ... from course").as(courseP *) for a list of Courses, or SQL("select ...").as(courseP.singleOpt) for an Option[Course].

Upvotes: 2

Related Questions