How to run Play Framework model methods from the Play console

Here’s a quick look at how to run Play Framework “model” methods from the Play console. In my case, my model methods are Anorm database access methods, but you may be accessing MongoDB, Cassandra, CouchDB, whatever.

First, move to your Play application directory and start the Play interpreter:

$ play

Then start the Play console:

[MyApp] $ console

Your prompt will now look like this:

scala> _

Next, use this magic line to launch your Play app:

scala> new play.core.StaticApplication(new java.io.File("."))

(I found that magic piece of code at this url.)

Now import your model (or models):

scala> import models._

Now you can run your model database methods. Here’s an example where I run an Anorm database-access method named selectAll on my Project model:

scala> Project.selectAll()
res1: List[models.Project] = List(Project(1,1,Focus,1,2014-04-13 14:12:40.0), Project(2,1,Finance,2,2014-04-13 14:12:40.0), Project(3,1,aa.com,3,2014-04-13 14:12:40.0), Project(4,1,Personal,4,2014-04-13 14:12:40.0))

Success!

Finally, for bonus points, make the output all pretty-like by adding mkString:

scala> Project.selectAll().mkString("\n")
res2: String =
Project(1,1,Focus,1,2014-04-13 14:12:40.0)
Project(2,1,Finance,2,2014-04-13 14:12:40.0)
Project(3,1,aa.com,3,2014-04-13 14:12:40.0)
Project(4,1,Personal,4,2014-04-13 14:12:40.0)

You’re welcome. ;)

Post new comment

The content of this field is kept private and will not be shown publicly.