Guide to Ebean ORM

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:

<dependency>
    <groupId>io.ebean</groupId>
    <artifactId>ebean</artifactId>
    <version>11.22.4</version>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.196</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>

The latest versions of Ebean, H2, and Logback 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:

<plugin>
    <groupId>io.ebean</groupId>
    <artifactId>ebean-maven-plugin</artifactId>
    <version>11.11.2</version>
    <executions>
        <execution>
            <id>main</id>
            <phase>process-classes</phase>
            <configuration>
                <transformArgs>debug=1</transformArgs>
            </configuration>
            <goals>
                <goal>enhance</goal>
            </goals>
        </execution>
    </executions>
</plugin>

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 ebean.mf:

entity-packages: com.baeldung.ebean.model
transactional-packages: com.baeldung.ebean.app

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 EbeanServer 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 application.properties, ebean.properties 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:

ebean.db.ddl.generate=true
ebean.db.ddl.run=true

datasource.db.username=sa
datasource.db.password=
datasource.db.databaseUrl=jdbc:h2:mem:customer
datasource.db.databaseDriver=org.h2.Driver

3.2. Using ServerConfig

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

ServerConfig cfg = new ServerConfig();

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

cfg.loadFromProperties(properties);
EbeanServer server = EbeanServerFactory.create(cfg);

3.3. Default Server Instance

A single EbeanServer instance maps to a single database. Depending on our requirements we could create more than one EbeanServer 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 Ebean class:

EbeanServer server = Ebean.getDefaultServer();

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

cfg.setDefaultServer(true);

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:

@MappedSuperclass
public abstract class BaseModel {

    @Id
    protected long id;

    @Version
    protected long version;

    @WhenCreated
    protected Instant createdOn;

    @WhenModified
    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:

@Entity
public class Customer extends BaseModel {

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

    private String name;

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

    // getters and setters
}
@Entity
public class Address extends BaseModel{

    public Address(String addressLine1, String addressLine2, String city) {
        super();
        this.addressLine1 = addressLine1;
        this.addressLine2 = addressLine2;
        this.city = 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 EbeanServer 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 Ebean 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);

EbeanServer server = Ebean.getDefaultServer();
server.save(c1);

c1.setName("Jane Wide");
c1.setAddress(null);
server.save(c1);

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

Ebean.delete(foundC1);

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 Ebean 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 = Ebean.find(Customer.class)
            .select("name")
            .fetch("address", "city")
            .where()
            .eq("city", "San Jose")
            .findOne();

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:

@Transactional
public static void insertAndDeleteInsideTransaction() {
    Customer c1 = getCustomer();
    EbeanServer server = Ebean.getDefaultServer();
    server.save(c1);
    Customer foundC1 = server.find(Customer.class, c1.getId());
    server.delete(foundC1);
}

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.

Leave a Reply

Your email address will not be published.