VOOZH about

URL: https://www.baeldung.com/active-jdbc

⇱ Introduction to ActiveJDBC | Baeldung


πŸ‘ Image
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)
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

ActiveJDBC is a lightweight ORM following the core ideas of ActiveRecord, the primary ORM of Ruby on Rails.

It focuses on simplifying the interaction with databases by removing the extra layer of typical persistence managers and focuses on the usage of SQL rather than creating a new query language.

Additionally, it provides its own way of writing unit tests for the database interaction through the DBSpec class.

Let’s see how this library differs from other popular Java ORMs and how to use it.

2. ActiveJDBC vs Other ORMs

ActiveJDBC has stark differences compared to most other Java ORMs. It infers the DB schema parameters from a database, thus removing the need for mapping entities to underlying tables.

No sessions, no persistence managers, no need to learn a new query language, no getters/setters. The library itself is light in terms of size and number of dependencies.

This implementation encourages the usage of test databases which are cleaned up by the framework after executing the tests, thus reducing the cost of maintaining test databases.

However, a little extra step of instrumentation is needed whenever we create or update model. We’ll discuss this in coming sections.

3. Design Principles

  • Infers metadata from DB
  • Convention-based configuration
  • No sessions, no β€œattaching, re-attaching”
  • Lightweight Models, simple POJOs
  • No proxying
  • Avoidance of Anemic Domain Model
  • No need of DAOs and DTOs

4. Setting Up the Library

A typical Maven setup for working with a MySQL database includes:

<dependency>
 <groupId>org.javalite</groupId>
 <artifactId>activejdbc</artifactId>
 <version>3.4-j11</version>
</dependency>
<dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>8.0.32</version>
</dependency>

The latest version of activejdbc and mysql connector artifacts can be found on the Maven Central repository.

Instrumentation is the price of simplification and needed when working with ActiveJDBC projects.

There’s an instrumentation plugin which needs to be configured in the project:

<plugin>
 <groupId>org.javalite</groupId>
 <artifactId>activejdbc-instrumentation</artifactId>
 <version>3.4-j11</version>
 <executions>
 <execution>
 <phase>process-classes</phase>
 <goals>
 <goal>instrument</goal>
 </goals>
 </execution>
 </executions>
</plugin>

The latest activejdbc-instrumentation plugin can also be found in Maven Central.

And now, we can process instrumentation by doing one of these two commands:

mvn process-classes
mvn activejdbc-instrumentation:instrument

5. Using ActiveJDBC

5.1. The Model

We can create a simple model with just one line of code – it involves extending the Model class.

The library uses inflections of the English language to achieve conversions of plural and singular forms of nouns. This can be overridden using the @Table annotation.

Let’s see how a simple model looks like:

import org.javalite.activejdbc.Model;

public class Employee extends Model {}

5.2. Connecting to a Database

Two classes – Base and DB – are provided to connect to databases.

The simplest way to connect to a database is:

Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://host/organization", "user", "xxxxx");

When models are in operation, they utilize a connection found in the current thread. This connection is put on the local thread by the Base or DB class before any DB operation.

The above approach allows for a more concise API, removing the need for DB Session or Persistence managers like in other Java ORMs.

Let’s see how to use the DB class to connect to a database:

new DB("default").open(
 "com.mysql.jdbc.Driver", 
 "jdbc:mysql://localhost/dbname", 
 "root", 
 "XXXXXX");

If we look at how differently Base and DB are used to connect to databases, it helps us conclude that Base should be used if operating on a single database and DB should be used with multiple databases.

5.3. Inserting Record

Adding a record to the database is very simple. As mentioned before, there’s no need for setters and getters:

Employee e = new Employee();
e.set("first_name", "Hugo");
e.set("last_name", "Choi");
e.saveIt();

Alternatively, we can add the same record this way:

Employee employee = new Employee("Hugo","Choi");
employee.saveIt();

Or even, fluently:

new Employee()
 .set("first_name", "Hugo", "last_name", "Choi")
 .saveIt();

5.4. Updating Record

The snippet below shows how to update a record:

Employee employee = Employee.findFirst("first_name = ?", "Hugo");
employee
 .set("last_name","Choi")
 .saveIt();

5.5. Deleting Record

Employee e = Employee.findFirst("first_name = ?", "Hugo");
e.delete();

If there is a need to delete all records:

Employee.deleteAll();

If we want to delete a record from a master table which cascades to child tables, use deleteCascade:

Employee employee = Employee.findFirst("first_name = ?","Hugo");
employee.deleteCascade();

5.6. Fetching a Record

Let’s fetch a single record from the database:

Employee e = Employee.findFirst("first_name = ?", "Hugo");

If we want to fetch multiple records, we can use the where method:

List<Employee> employees = Employee.where("first_name = ?", "Hugo");

6. Transaction Support

In Java ORMs, there is an explicit connection or a manager object (EntityManager in JPA, SessionManager in Hibernate, etc.). There’s no such thing in ActiveJDBC.

The call Base.open() opens a connection, attaches it to the current thread and thus all subsequent methods of all models reuse this connection. The call Base.close() closes the connection and removes it from the current thread.

To manage transactions, there are are few convenience calls:

Starting a transaction:

Base.openTransaction();

Committing a transaction:

Base.commitTransaction();

Rolling back a transaction:

Base.rollbackTransaction();

7. Supported Databases

The latest version supports databases of likes SQLServer, MySQL, Oracle, PostgreSQL, H2, SQLite3, DB2.

8. Conclusion

In this quick tutorial, we focused on and explored the very basics of ActiveJDBC.

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)