Skip to content
javahacks.dev
Play Framework

How to Use Play With Ebean or JPA for Database Access

Add a database to a Play application with the Ebean plugin or with JPA and Hibernate, configure the connection and pick the one that fits your team.

6 min read
Summarize in AI
Flat illustration of a database beside the table it holds, with the Hibernate, MongoDB, Redis, MySQL and PostgreSQL logos.

Play does not include an ORM. It integrates two of them, Ebean and JPA with Hibernate, and which one you pick shapes the rest of the application: how models are written, how transactions are handled and how much of your existing knowledge carries over. This guide sets up the database connection that both share, then Ebean, then JPA, explains how to keep blocking database calls off the request threads, covers schema management with evolutions and gives a rule for choosing. It targets a current Play 3 project on JDK 25. The persistence concepts for the JPA option are in Hibernate and JPA without the surprises, and a first project is in the Play tutorial.

The connection

Both options read the same configuration:

conf/application.confText
db.default.driver = org.postgresql.Driver
db.default.url = "jdbc:postgresql://localhost:5432/shop"
db.default.username = shop
db.default.password = ${?DB_PASSWORD}

The syntax ${?DB_PASSWORD} reads the environment variable if it is set and leaves the key undefined otherwise, which keeps the password out of the file. Put the real value in the environment of the process or in a secret store. Add the PostgreSQL driver to build.sbt:

build.sbtscala
libraryDependencies += "org.postgresql" % "postgresql" % "42.7.4"

Play uses HikariCP for the pool and exposes its settings under play.db.prototype.hikaricp. Check the maximum pool size early: the default is small, and it needs to fit the database's connection limit across all instances of the application.

Option 1: Ebean

Add the plugin in project/plugins.sbt and enable it for the project. The plugin version must match your Play release, so check the plugin's README for its compatibility table before copying the number below:

project/plugins.sbtscala
addSbtPlugin("org.playframework" % "sbt-play-ebean" % "8.0.0")
build.sbtscala
lazy val root = (project in file(".")).enablePlugins(PlayJava, PlayEbean)
conf/application.confText
ebean.default = ["models.*"]

A model extends io.ebean.Model:

app/models/Product.javajava
@Entity
public class Product extends Model {

    @Id
    public Long id;

    public String name;

    public long priceCents;

    public static final Finder<Long, Product> find = new Finder<>(Product.class);
}

Then Product.find.all(), Product.find.byId(1L) and product.save() work. Ebean enhances the class at build time to track changes, so there is no session to open, no detached-entity problem and no lazy-loading exception to learn. It has a fluent query API with joins and filters. The model is simpler than JPA and also less flexible: the active-record style puts persistence into the model class, which makes unit testing the model harder, and some complex mappings are awkward.

Option 2: JPA with Hibernate

Add the JPA support and the provider. Use the Hibernate version that the Play JPA guide names for your release, because the integration is built against a specific one:

build.sbtscala
libraryDependencies ++= Seq(javaJpa, "org.hibernate.orm" % "hibernate-core" % "6.6.4.Final")
conf/application.confText
jpa.default = defaultPersistenceUnit

Create conf/META-INF/persistence.xml naming the persistence unit and the entity classes. Use the JPAApi in a repository:

java
public class ProductRepository {

    private final JPAApi jpa;

    @Inject
    public ProductRepository(JPAApi jpa) { this.jpa = jpa; }

    public Product find(Long id) {
        return jpa.withTransaction(em -> em.find(Product.class, id));
    }
}

withTransaction runs the lambda in a transaction on the calling thread and commits afterwards. Everything in the Hibernate guide applies: lazy loading, fetch plans and the persistence context, including the exception when an association is read after the transaction has ended. Entities are plain classes, so you can reuse them in tests and in other modules, and developers who know Hibernate from Spring are productive at once.

Keep blocking calls off request threads

Play's default dispatcher is small, and JDBC blocks. A request thread that waits on the database is a thread that cannot serve another request. Give database work its own executor:

conf/application.confText
database.dispatcher {
  executor = "thread-pool-executor"
  throttling = off
  thread-pool-executor { fixed-pool-size = 20 }
}

Run queries with CompletableFuture.supplyAsync(() -> repo.find(id), executionContext), where the execution context is the one bound to this dispatcher. Size the pool to the database connection pool, not to the request load: more threads than connections only queue. If the number of blocking calls is large and your JDK is recent, virtual threads offer a simpler way to scale blocking code, with the caveats in Reactor versus virtual threads.

Schema with evolutions

Play evolutions apply SQL scripts from conf/evolutions/default/1.sql, 2.sql, in order, each with # --- !Ups and # --- !Downs sections:

SQL
# --- !Ups
create table product (id bigserial primary key, name varchar(200) not null, price_cents bigint not null);

# --- !Downs
drop table product;

Play records which evolutions ran in a table, applies the new ones on start in development and, in production, requires an explicit setting before it will change the schema on start. Treat the Downs sections as documentation rather than a rollback plan, since dropping a table loses data. Evolutions are fine for a small application. For larger ones, Flyway or Liquibase give better tooling for review, checksums and repeatable migrations.

Which to pick

ChooseWhen
EbeanA small application, a team new to ORMs, fast CRUD
JPA with HibernateExisting Hibernate knowledge, complex mappings, shared code with Spring services

The decision is also about the lifetime of the code. Ebean ties your models to Play's tooling, while JPA entities are portable if the application later moves to another framework. If you expect to share domain code with other services, take JPA from the start.

Testing the data layer

Run repository tests against the real database engine, using Testcontainers or a dedicated test database, not an in-memory substitute, because SQL differences hide behind H2. Reset state per test through evolutions or a cleanup step, and keep tests independent of each other. The testing layers for a Play application are described in testing Play applications.

Migrating between the two

Moving from Ebean to JPA is a rewrite of the model classes and the code that calls find and save, while the tables stay the same. Do it one aggregate at a time behind a repository interface, so the callers do not change. Keep the repository interface free of ORM types and return plain objects, which also makes the controller tests simple. The reverse direction is shorter, since Ebean needs less ceremony, but it loses the portability that was the reason to prefer JPA.

Configuration worth checking in production

Set the pool size and the connection timeout explicitly. Turn off any automatic schema creation in production, and make the application fail at start when the schema does not match, which validate mode does for JPA. Log slow queries at the database. And check that the database user has only the rights the application needs: a migration tool needs more than the running service does, so use two accounts if you can.

When an ORM is the wrong tool

For heavy reporting, use SQL directly through the Database API and JDBC, which gives you control of the query and the result shape. The references are the Play database documentation and Ebean's documentation. If dependencies fail to resolve after a version change, see compile errors after upgrading sbt.

Also inHibernate
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.