Play Framework 2 Tutorial: Database Access
How to configure and access a database in the Play Framework.
In this post, part four of the tutorial series about the Play Framework, I’ll talk about database configuration and access.
Configuring JDBC Connection Pool
In order to start accessing a database in your app, you first have to enable a connection pool. Here we’ll enable the default H2 (in-memory) data source by uncommenting the following lines in conf/application.conf
:
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
Play includes a JDBC driver for H2 by default so there’s no need to add it to your application, however when you’re ready to deploy your app to production you’ll have to add a driver. For example, to support access to a MySQL database you’ll update project/Build.scala
with the following:
val appDependencies = Seq(
// Add your project dependencies here,
"mysql" % "mysql-connector-java" % "5.1.18"
)
If you prefer PostgreSQL, then update project/Build.scala
with the following:
val appDependencies = Seq(
// Add your project dependencies here,
"postgresql" % "postgresql" % "9.1-901-1.jdbc4"
)
If you’re planning on deploying your app to Heroku, you’ll also update your Procfile
with:
web: target/start -Dhttp.port=${PORT} -DapplyEvolutions.default=true -Ddb.default.driver=org.postgresql.Driver -Ddb.default.url=$DATABASE_URL ${JAVA_OPTS}
Accessing the Database
Now that you have a default data source configured. Let’s test the configuration.
import org.junit.Test;
import org.springframework.util.Assert;
import play.db.DB;
import javax.sql.DataSource;
import java.sql.Connection;
import static play.test.Helpers.fakeApplication;
import static play.test.Helpers.running;
public class DataSourceTest {
@Test
public void testGetDataSource() {
running(fakeApplication(), new Runnable() {
@Override
public void run() {
DataSource ds = DB.getDataSource();
Assert.notNull(ds, "DataSource was null!");
}
});
}
@Test
public void testGetConnection() {
running(fakeApplication(), new Runnable() {
@Override
public void run() {
Connection conn = DB.getConnection();
Assert.notNull(conn, "Connection was null!");
}
});
}
}
If the above tests pass you now have confidence that the database is configured properly and you can move on to making use of Ebean or JPA implementation which I’ll cover in future posts.