0

Is it bad practice in Play! Framework to define the implicit DB session inside the controller to have less boilerplate?

object MyController extends Controller  {
  implicit val session = DB.createSession
}

I'm not sure about the life cycle of controllers in Play!, can somebody enlighten me?

Martijn
  • 2,268
  • 3
  • 25
  • 51
Alexej Haak
  • 480
  • 3
  • 10

1 Answers1

2

I see multiple problems having implicit db session inside the controller.

  1. Db sessions should be created when needed and then destroyed as soon as your queries are executed. The reason being that each session will use one connection to the db. Your db can handle x number of connections. After that, the db will grind to a halt.

    Now as each controller will have one connection to the db and those connections will not be closed, after some number of controllers, your application's performance will be drastically reduced.

  2. As each controller will have only one session, multiple queries will be executed sequentially i.e one request to controller will use the session to execute the query and till the query is executed, any other request to the same controller(i.e to any other method to the same controller) will have to wait.

  3. You will not be able to use any connection pooling library as you will create a single session and use it throughout.

Community
  • 1
  • 1
mohit
  • 4,968
  • 1
  • 22
  • 39
  • This is not completely true, it is possible to use Beans as controllers coupled with dependency autowiring, this would result in the same behavior as described by you though. I'm not quite sure if these objects are kept between different requests but I guess they are. – Martijn Jan 19 '15 at 15:09
  • @MartijnRiemers Thanks. I was not sure about that. I have removed that. However, I am sure that it will not be a good idea to create a single session at the start of the controller to remove boilerplate code. – mohit Jan 19 '15 at 15:12
  • That I totally agree with :) – Martijn Jan 19 '15 at 15:15
  • So where should the implicit session be created? In action handlers or further down in the data access layer per method (e.g. findObject, createObject, etc.)? – jbrown Jan 20 '15 at 18:00
  • Depends on your design. Create your sessions wherever you need them and close it afterwards which is also given in docs. From http://slick.typesafe.com/doc/2.1.0/connection.html, `You usually do not want to keep sessions open for very long but open and close them quickly when needed. ` – mohit Jan 20 '15 at 19:20