Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:


1. Introduction

Ebean is an object-relational mapping tool written in Java.

It supports the standard JPA annotations for declaring entities. However, it provides a much simpler API for persisting. In fact, one of the points worth mentioning about the Ebean architecture is that it is sessionless, meaning it does not fully manage entities.

Besides that, it also comes with a query API and supports writing queries in native SQL. Ebean supports all major database providers such as Oracle, Postgres, MySql, H2 etc.

In this tutorial, we’ll take a look at how we can create, persist and query entities using Ebean and H2.

2. Setup

To get started, let’s get our dependencies as well as some basic configuration.

2.1. Maven Dependencies

Before we begin, let’s import the required dependencies:


The latest versions of Ebean and H2 can be found on Maven Central.

2.2. Enhancements

Ebean needs to modify entity beans so that they can be managed by the server. Thus, we’ll add a Maven plugin to do that job:


We also need to provide the Maven plugin with the names of the packages which contain the entities and classes which use transactions. To do that we create the file

entity-packages: com.baeldung.ebean.model

2.3. Logging

Let’s also create logback.xml and set logging levels on some packages to TRACE so that we can see the statements that are being executed:

<logger name="io.ebean.DDL" level="TRACE"/>
<logger name="io.ebean.SQL" level="TRACE"/>
<logger name="io.ebean.TXN" level="TRACE"/>

3. Configuring a Server

We need to create an Database instance to save entities or run queries on a database. There are two ways in which we can create a server instance – using a default properties file or doing it programmatically.

3.1. Using a Default Properties File

The default properties file can be of type properties or yaml. Ebean will search for configuration in files with names, or application.yml.

Apart from supplying the database connection details, we can also instruct Ebean to create and run DDL statements.

Now, let’s look at a sample configuration:



3.2. Using DatabaseConfig

Next, let’s look at how we can create the same server programmatically using DatabaseFactory and DatabaseConfig:

DatabaseConfig cfg = new DatabaseConfig();

Properties properties = new Properties();
properties.put("ebean.db.ddl.generate", "true");
properties.put("", "true");
properties.put("datasource.db.username", "sa");
properties.put("datasource.db.password", "");
properties.put("datasource.db.databaseDriver", "org.h2.Driver");

Database server = DatabaseFactory.create(cfg);

3.3. Default Server Instance

A single Database instance maps to a single database. Depending on our requirements we could create more than one Database instance as well.

If only a single server instance is created, by default, it is registered as the default server instance. It can be accessed anywhere in the application using a static method on the DB class:

Database server = DB.getDefault();

In case there are multiple databases, it’s possible to register one of the server instances as default one:


4. Creating Entities

Ebean provides full support for JPA annotations as well as additional features using its own annotations.

Let’s create few entities using both JPA and Ebean annotations. First, we’ll create a BaseModel which contains properties that are common across entities:

public abstract class BaseModel {

    protected long id;
    protected long version;
    protected Instant createdOn;
    protected Instant modifiedOn;

    // getters and setters

Here, we have used the MappedSuperClass JPA annotation to define the BaseModel.  And two Ebean annotations io.ebean.annotation.WhenCreated and io.ebean.annotation.WhenModified for auditing purposes.

Next, we will create two entities Customer and Address which extend BaseModel:

public class Customer extends BaseModel {

    public Customer(String name, Address address) {
        super(); = name;
        this.address = address;

    private String name;

    @OneToOne(cascade = CascadeType.ALL)
    Address address;

    // getters and setters

public class Address extends BaseModel {

    public Address(String addressLine1, String addressLine2, String city) {
        this.addressLine1 = addressLine1;
        this.addressLine2 = addressLine2; = city;
    private String addressLine1;
    private String addressLine2;
    private String city;

    // getters and setters

In Customer, we have defined a one to one mapping with Address and added set cascade type to ALL so that child entities are also updated along with the parent entities.

5. Basic CRUD Operations

Earlier we’ve seen how to configure the Database and created two entities. Now, let’s carry out some basic CRUD operations on them.

We’ll be using the default server instance to persist and access the data. The DB class also provides static methods to persist and access data which proxy the request to default server instance:

Address a1 = new Address("5, Wide Street", null, "New York");
Customer c1 = new Customer("John Wide", a1);

Database server = DB.getDefault();;

c1.setName("Jane Wide");

Customer foundC1 = DB.find(Customer.class, c1.getId());


First, we create a Customer object and used the default server instance to save it using save().

Next, we’re updating the customer details and saving it again using save().

Finally, we’re using the static method find() on DB to fetch the customer and delete it using delete().

6. Queries

Query APIs can also be used to create an object graph with filters and predicates. We can either use Ebean or EbeanServer to create and execute queries.

Let’s look at a query which finds a Customer by city and returns a Customer and Address object with only some fields populated:

Customer customer = DB.find(Customer.class)
            .fetch("address", "city")
            .eq("city", "San Jose")

Here, with find() we indicate that we want to find entities of type Customer. Next, we use select() to specify the properties to populate in the Customer object.

Later, we use fetch() to indicate that we want to fetch the Address object belonging to the Customer and that we want to fetch the city field.

Finally, we add a predicate and restrict the size of the result to 1.

7. Transactions

Ebean executes each statement or query in a new transaction by default.

Although this may not be an issue in some cases. There are times when we may want to execute a set of statements within a single transaction.

In such cases, if we annotate the method with io.ebean.annotations.Transactional, all the statements within the method will be executed inside the same transaction:

public static void insertAndDeleteInsideTransaction() {
    Customer c1 = getCustomer();
    Database server = DB.getDefault();;
    Customer foundC1 = server.find(Customer.class, c1.getId());

8. Building the Project

Lastly, we can build the Maven project using the command:

compile io.ebean:ebean-maven-plugin:enhance

9. Conclusion

To sum up, we’ve looked at the basic features of Ebean which can be used to persist and query entities in a relational database.

Finally, this code is available on Github.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

res – Persistence (eBook) (cat=Persistence)
Comments are closed on this article!