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 or Collection 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 full source code of the example can be found over on GitHub.


« 上一篇: Deeplearning4J的指南
» 下一篇: JIRA REST API 集成