1. Introduction

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

Even though 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. Therefore, it does not fully manage entities. Additionally, it allows us to query all major databases natively using SQL. For example, it supports providers such as Oracle, Postgres, MySql, H2, etc.

Now, we’ll start by creating and persisting data. Then, we will query entities using Ebean and H2.

2. Setup

First, let’s configure our project by adding the required dependencies.

2.1. Maven Dependencies

Now, let’s add our maven dependencies to the pom.xml file:

<dependency>
    <groupId>io.ebean</groupId>
    <artifactId>ebean</artifactId>
    <version>13.25.2</version>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>2.1.214</version>
</dependency>

Here, we must use the latest versions of Ebean and H2.

2.2. Enhancements

Then, Ebean needs to modify entity beans so that the server can manage them. For this purpose, we’ll add the ebean-maven-plugin to achieve the required behavior:

<plugin>
    <groupId>io.ebean</groupId>
    <artifactId>ebean-maven-plugin</artifactId>
    <version>13.25.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>

Additionally, we also need to tell the Maven plugin the names of the packages that contain the entities and classes using transactions. Thus, we create the file ebean.mf:

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

2.3. Logging

Finally, we’ll 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

Next, we’ll create a 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. Let’s explore them both.

3.1. Using a Default Properties File

First, Ebean will search for configuration in files with names application.properties, ebean.properties, or application.yml. So, both .properties and .yaml are compatible with Ebean.

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 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("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);
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 the default one:

cfg.setDefaultServer(true);

4. Creating Entities

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

Let’s create a 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 set cascade type to ALL so that child entities are also updated along with the parent entities.

5. Basic CRUD Operations

Earlier, we saw how to configure the Database and create 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 the default server instance:

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

Database server = DB.getDefault();
server.save(c1);

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

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

DB.delete(foundC1);

First, we created 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 that finds a Customer by city and returns a Customer and Address object with only some fields populated:

Customer customer = DB.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();
    Database server = DB.getDefault();
    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, the full code is available over on GitHub.

Course – LSD (cat=Persistence)

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

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.