Calling a database from inside Play using Ebean

Rowan Laurence
Beyond
Published in
2 min readJan 23, 2018

Part three of a series

This application uses Ebean as an ORM to manage database queries and models — you can read the Ebean docs here. Be aware that Play and Ebean are separate projects, and versions are not always in line with each other.

Creating tables and evolutions

When setting up any project you will want to stub out the tables you’re going to use as SQL definitions to make sure things like indexes are created and any foreign keys are mapped.

We have set some up for this project — they are super simple and live in the conf/evolutions folder.

It’s a pretty simple task to edit 1.sql to create your tables, and 2.sql to create your data. There are 3 charities, that’s 3 records and a counter.

The data model as an Ebean annotated class living in /models/Charity.java

You can write some really complicated models very easily in Ebean with Play, (read more about Ebean and Play here) but for now this is a very simple model.

Now, how do we get the data out of the DB?

If you open the file repository/CharityRepository.java you can see the following method:

This method will go to the database and fetch all records as defined by the Charity model, that was it. This writes all of your SQL for you, reads the data from the DB, and converts into Charity models.

Next >> Asynchronous programming with Akka and Actors, in Play Framework

--

--

Rowan Laurence
Beyond
Writer for

Technical Director at Beyond San Francisco — Interested in all things digital, scalable software, collecting shoes and dance music