eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)