Skip to content
This repository has been archived by the owner on Jan 17, 2022. It is now read-only.

Database connection pool example with c3p0 #19

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
3 changes: 2 additions & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
}