Permalink
Browse files

database connection pool example

  • Loading branch information...
1 parent 1fc97d5 commit 96769660f7fbbec4a1e8367f26ec26152a63a0a6 @fernandezpablo85 committed Apr 8, 2013
Showing with 59 additions and 1 deletion.
  1. +2 −0 README.txt
  2. +2 −1 build.sbt
  3. +55 −0 src/main/scala/com/typesafe/slick/examples/lifted/ConnectionPool.scala
View
@@ -27,3 +27,5 @@ of all available examples:
* CallNativeDBFunction: Shows how to use a database function which is not
provided by the SLICK driver in the Query Language.
+
+* ConnectionPool: Example of how to use Slick with a database connection pool
View
@@ -17,7 +17,8 @@ libraryDependencies ++= List(
"com.typesafe.slick" %% "slick" % "1.0.0",
"org.slf4j" % "slf4j-nop" % "1.6.4",
"com.h2database" % "h2" % "1.3.170",
- "org.xerial" % "sqlite-jdbc" % "3.6.20"
+ "org.xerial" % "sqlite-jdbc" % "3.6.20",
+ "c3p0" % "c3p0" % "0.9.1.2"
/*
"org.apache.derby" % "derby" % "10.6.1.0",
"org.hsqldb" % "hsqldb" % "2.0.0",
@@ -0,0 +1,55 @@
+package com.typesafe.slick.examples.lifted
+
+import scala.slick.driver.PostgresDriver.simple._
+import Database.threadLocalSession
+import com.mchange.v2.c3p0.ComboPooledDataSource
+
+/* Connection pooling with c3p0 example.
+ * For a more detailed explanation see:
+ * http://fernandezpablo85.github.io/2013/04/07/slick_connection_pooling.html
+ */
+object ConnectionPool extends App {
+
+ case class User(id: Option[Int], name: String, last: String) {
+ override def toString = last + ", " + name
+ }
+
+ object Users extends Table[User]("users") {
+ def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
+ def name = column[String]("name")
+ def lastName = column[String]("last_name")
+
+ def * = (id.? ~ name ~ lastName) <> (User, User.unapply _)
+ }
+
+ // the pool can be fully configured.
+ // http://www.mchange.com/projects/c3p0/
+ val datasource = new ComboPooledDataSource
+ datasource.setDriverClass("org.h2.Driver")
+ datasource.setJdbcUrl("jdbc:h2:mem:test1")
+
+ Database.forDataSource(datasource) withSession {
+
+ // create schema.
+ Users.ddl.create
+
+ // insert a few users.
+ Users.insert(User(None, "pablo", "fernandez"))
+ Users.insert(User(None, "noob", "saibot"))
+ Users.insert(User(None, "vincent", "vega"))
+
+ // query by last name.
+ val lastName = "fernandez"
+ val users = (for (u <- Users if u.lastName is lastName) yield (u)).list
+
+ // print results.
+ if (users.isEmpty)
+ println(s"no users with last name '$lastName'")
+ else {
+ println(s"users with last name '$lastName':")
+ users foreach { user =>
+ println(user)
+ }
+ }
+ }
+}

0 comments on commit 9676966

Please sign in to comment.