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. Overview

ORMLite is a lightweight ORM library for Java applications. It provides standard features of an ORM tool for the most common use cases, without the added complexity and overhead of other ORM frameworks.

It’s main features are:

  • defining entity classes by using Java annotations
  • extensible DAO classes
  • a QueryBuilder class for creating complex queries
  • generated classes for creating and dropping database tables
  • support for transactions
  • support for entity relationships

In the next sections, we’ll take a look at how we can set up the library, define entity classes and perform operations on the database using the library.

2. Maven Dependencies

To start using ORMLite, we need to add the ormlite-jdbc dependency to our pom.xml:

<dependency>
    <groupId>com.j256.ormlite</groupId>
    <artifactId>ormlite-jdbc</artifactId>
    <version>6.1</version>
</dependency>

By default, this also brings in the h2 dependency. In our examples, we’ll use an H2 in-memory database, so we don’t need another JDBC driver.

If you want to use a different database, you’ll also need the corresponding dependency.

3. Defining Entity Classes

To set up our model classes for persistence with ORMLite, there are two primary annotations we can use:

  • @DatabaseTable for the entity class
  • @DatabaseField for the properties

Let’s start by defining a Library entity with a name field and a libraryId field which is also a primary key:

@DatabaseTable(tableName = "libraries")
public class Library {	
 
    @DatabaseField(generatedId = true)
    private long libraryId;

    @DatabaseField(canBeNull = false)
    private String name;

    public Library() {
    }
    
    // standard getters, setters
}

The @DatabaseTable annotation has an optional tableName attribute that specifies the name of the table if we don’t want to rely on a default class name.

For every field that we want to persist as a column in the database table, we have to add the @DatabaseField annotation.

The property that will serve as a primary key for the table can be marked with either id, generatedId or generatedSequence attributes. In our example, we choose the generatedId=true attribute so that the primary key will be automatically incremented.

Also, note that the class needs to have a no-argument constructor with at least package-scope visibility.

A few other familiar attributes we can use for configuring the fields are columnName, dataType, defaultValue, canBeNull, unique.

3.1. Using JPA Annotations

In addition to the ORMLite-specific annotations, we can also use JPA-style annotations to define our entities.

The equivalent of the Library entity we defined before using JPA standard annotations would be:

@Entity
public class LibraryJPA {
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long libraryId;

    @Column
    private String name;
    
    // standard getters, setters
}

Although ORMLite recognizes these annotations, we still need to add the javax.persistence-api dependency to use them.

The full list of supported JPA annotations is @Entity, @Id, @Column, @GeneratedValue, @OneToOne, @ManyToOne, @JoinColumn, @Version.

4. ConnectionSource

To work with the objects defined, we need to set up a ConnectionSource.

For this, we can use the JdbcConnectionSource class which creates a single connection, or the JdbcPooledConnectionSource which represents a simple pooled connection source:

JdbcPooledConnectionSource connectionSource 
  = new JdbcPooledConnectionSource("jdbc:h2:mem:myDb");

// work with the connectionSource

connectionSource.close();

Other external data source with better performance can also be used, by wrapping them in a DataSourceConnectionSource object.

5. TableUtils Class

Based on the ConnectionSource, we can use static methods from the TableUtils class to perform operations on the database schema:

  • createTable() – to create a table based on a entity class definition or a DatabaseTableConfig object
  • createTableIfNotExists() – similar to the previous method, except it will only create the table if it doesn’t exist; this only works on databases that support it
  • dropTable() – to delete a table
  • clearTable() – to delete the data from a table

Let’s see how we can use TableUtils to create the table for our Library class:

TableUtils.createTableIfNotExists(connectionSource, Library.class);

6. DAO Objects

ORMLite contains a DaoManager class that can create DAO objects for us with CRUD functionality:

Dao<Library, Long> libraryDao 
  = DaoManager.createDao(connectionSource, Library.class);

The DaoManager doesn’t regenerate the class for each subsequent call of createDao(), but instead reuses it for better performance.

Next, we can perform CRUD operations on Library objects:

Library library = new Library();
library.setName("My Library");
libraryDao.create(library);
        
Library result = libraryDao.queryForId(1L);
        
library.setName("My Other Library");
libraryDao.update(library);
        
libraryDao.delete(library);

The DAO is also an iterator that can loop through all the records:

libraryDao.forEach(lib -> {
    System.out.println(lib.getName());
});

However, ORMLite will only close the underlying SQL statement if the loop goes all the way to the end. An exception or a return statement may cause a resource leak in your code.

For that reason, the ORMLite documentation recommends we use the iterator directly:

try (CloseableWrappedIterable<Library> wrappedIterable 
  = libraryDao.getWrappedIterable()) {
    wrappedIterable.forEach(lib -> {
        System.out.println(lib.getName());
    });
 }

This way, we can close the iterator using a try-with-resources or a finally block and avoid any resource leak.

6.1. Custom DAO Class

If we want to extend the behavior of the DAO objects provided, we can create a new interface which extends the Dao type:

public interface LibraryDao extends Dao<Library, Long> {
    public List<Library> findByName(String name) throws SQLException;
}

Then, let’s add a class that implements this interface and extends the BaseDaoImpl class:

public class LibraryDaoImpl extends BaseDaoImpl<Library, Long> 
  implements LibraryDao {
    public LibraryDaoImpl(ConnectionSource connectionSource) throws SQLException {
        super(connectionSource, Library.class);
    }

    @Override
    public List<Library> findByName(String name) throws SQLException {
        return super.queryForEq("name", name);
    }
}

Note that we need to have a constructor of this form.

Finally, to use our custom DAO, we need to add the class name to the Library class definition:

@DatabaseTable(tableName = "libraries", daoClass = LibraryDaoImpl.class)
public class Library { 
    // ...
}

This enables us to use the DaoManager to create an instance of our custom class:

LibraryDao customLibraryDao 
  = DaoManager.createDao(connectionSource, Library.class);

Then we can use all the methods from the standard DAO class, as well as our custom method:

Library library = new Library();
library.setName("My Library");

customLibraryDao.create(library);
assertEquals(
  1, customLibraryDao.findByName("My Library").size());

7. Defining Entity Relationships

ORMLite uses the concept of “foreign” objects or collections to define relationships between entities for persistence.

Let’s take a look at how we can define each type of field.

7.1. Foreign Object Fields

We can create a unidirectional one-to-one relationship between two entity classes by using the foreign=true attribute on a field annotated with @DatabaseField. The field must be of a type that’s also persisted in the database.

First, let’s define a new entity class called Address:

@DatabaseTable(tableName="addresses")
public class Address {
    @DatabaseField(generatedId = true)
    private long addressId;

    @DatabaseField(canBeNull = false)
    private String addressLine;
    
    // standard getters, setters 
}

Next, we can add a field of type Address to our Library class which is marked as foreign:

@DatabaseTable(tableName = "libraries")
public class Library {      
    //...

    @DatabaseField(foreign=true, foreignAutoCreate = true, 
      foreignAutoRefresh = true)
    private Address address;

    // standard getters, setters
}

Notice that we’ve also added two more attributes to the @DatabaseField annotation: foreignAutoCreate and foreignAutoRefresh, both set to true.

The foreignAutoCreate=true attribute means that when we save a Library object with an address field, the foreign object will also be saved, provided its id is not null and has a generatedId=true attribute.

If we set foreignAutoCreate to false, which is the default value, then we’d need to persist the foreign object explicitly before saving the Library object that references it.

Similarly, the foreignAutoRefresh=true attribute specifies that when retrieving a Library object, the associated foreign object will also be retrieved. Otherwise, we’d need to refresh it manually.

Let’s add a new Library object with an Address field and call the libraryDao to persist both:

Library library = new Library();
library.setName("My Library");
library.setAddress(new Address("Main Street nr 20"));

Dao<Library, Long> libraryDao 
  = DaoManager.createDao(connectionSource, Library.class);
libraryDao.create(library);

Then, we can call the addressDao to verify that the Address has also been saved:

Dao<Address, Long> addressDao 
  = DaoManager.createDao(connectionSource, Address.class);
assertEquals(1, 
  addressDao.queryForEq("addressLine", "Main Street nr 20")
  .size());

7.2. Foreign Collections

For the many side of a relationship, we can use the types ForeignCollection<T> or Collection<T> with a @ForeignCollectionField annotation.

Let’s create a new Book entity like the ones above, then add a one-to-many relationship in the Library class:

@DatabaseTable(tableName = "libraries")
public class Library {  
    // ...
    
    @ForeignCollectionField(eager=false)
    private ForeignCollection<Book> books;
    
    // standard getters, setters
}

In addition to this, it’s required that we add a field of type Library in the Book class:

@DatabaseTable
public class Book {
    // ...
    @DatabaseField(foreign = true, foreignAutoRefresh = true) 
    private Library library;

    // standard getters, setters
}

The ForeignCollection has add() and remove() methods that operate on the records of type Book:

Library library = new Library();
library.setName("My Library");
libraryDao.create(library);

libraryDao.refresh(library);

library.getBooks().add(new Book("1984"));

Here, we’ve created a library object, then added a new Book object to the books field, which also persists it to the database.

Note that since our collection is marked as lazily loaded (eager=false), we need to call the refresh() method before being able to use the book field.

We can also create the relationship by setting the library field in the Book class:

Book book = new Book("It");
book.setLibrary(library);
bookDao.create(book);

To verify that both Book objects are added to the library we can use the queryForEq() method to find all the Book records with the given library_id:

assertEquals(2, bookDao.queryForEq("library_id", library).size());

Here, the library_id is the default name of the foreign key column, and the primary key is inferred from the library object.

8. QueryBuilder

Each DAO can be used to obtain a QueryBuilder object that we can then leverage for building more powerful queries.

This class contains methods that correspond to common operations used in an SQL query such as: selectColumns(), where(), groupBy(), having(), countOf(), distinct(), orderBy(), join().

Let’s see an example of how we can find all the Library records that have more than one Book associated:

List<Library> libraries = libraryDao.queryBuilder()
  .where()
  .in("libraryId", bookDao.queryBuilder()
    .selectColumns("library_id")
    .groupBy("library_id")
    .having("count(*) > 1"))
  .query();

9. Conclusion

In this article, we’ve seen how we can define entities using ORMLite, as well as the main features of the library that we can use to manipulate objects and their associated relational databases.

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)