Im a newbie scala and scalatra developer. Im trying to integrate c3p0 to get connection pooling in my application.
All the examples on the scalatra page is with squeryl etc, but I dont want orm and dsl. Do anyone have a ok examples with scalatra and c3p0.
Thanks all :)
Note: None of the code below has been compiled or checked, i'm just writing it into my browser. apologies for the inevitable glitches.
So, I've never used Scalatra. But I wrote c3p0, and have used the Servlets API a lot. A quick look at scalatra's guides suggests something like this would work:
To get access to the DataSource from a ServletRequest object, you'd call...
You might want to use your Scala-fu to pimp ServletRequest and make access to the Connection pool easier and prettier. For example, you could write...
Put this in a package object or some object you import into your code, and while you handle requests you should be able to write stuff like...
However, the above is crappy, leak-prone code, because the close() isn't in a finally and will be skipped by an Exception. In Java7-style, you'd use try-with-resources to avoid this. In Scala, the naive way is to do this:
However, a better way in Scala is to define utility methods like this:
Then you can just write stuff like...
To really keep JDBC clean in scala, consider writing analogous methods like
withStatement
andwithResultSet
as well, so you can do