diff --git a/README.txt b/README.txt index c5e33db..f05d5b2 100644 --- a/README.txt +++ b/README.txt @@ -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 diff --git a/build.sbt b/build.sbt index 4abb670..1f0498f 100644 --- a/build.sbt +++ b/build.sbt @@ -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", diff --git a/src/main/scala/com/typesafe/slick/examples/lifted/ConnectionPool.scala b/src/main/scala/com/typesafe/slick/examples/lifted/ConnectionPool.scala new file mode 100644 index 0000000..f7bdd05 --- /dev/null +++ b/src/main/scala/com/typesafe/slick/examples/lifted/ConnectionPool.scala @@ -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) + } + } + } +}