Android Core

ObjectBox, a modern and easy to use Android database

If you’re familiar with libraries like greenDAO or EventBus, you may have heard of the company that created them: greenrobot. If not, I recommend checking them out. In short, they build high quality open source libraries for app developers.

Recently, they have come out with a new library called ObjectBox. It is used to help manage your app’s local data storage. Their older library greenDAO serves the same purpose, but ObjectBox is their next step in local storage solutions. The biggest difference is that ObjectBox does not use SQL at all.

Getting Started

To get started using it, you can check out their gradle setup. Once you have gradle setup, the library is easy to use. Simply create your data model classes as normal, and add the annotation @Entity. See an example below:

@Entity
public class Animal {
    @Id(assignable = true)
    private long id;

    private String name;

    private boolean flying;

    private boolean swimming;

    private boolean walking;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isFlying() {
        return flying;
    }

    public void setFlying(boolean flying) {
        this.flying = flying;
    }

    public boolean isSwimming() {
        return swimming;
    }

    public void setSwimming(boolean swimming) {
        this.swimming = swimming;
    }

    public boolean isWalking() {
        return walking;
    }

    public void setWalking(boolean walking) {
        this.walking = walking;
    }
}

ObjectBox needs access to the properties of your class, so you’ll need to make the appropriate setter and getter methods. Alternatively, you can remove the private modifier and ObjectBox’s generated classes will access them directly instead.

Now that you have your data models setup, you need to initialize the database. I prefer to do this in my Application class, but you could setup your own singleton or inject it with Dagger if you prefer. My application class looks like this:

public class App extends Application {

    private static App sApp;
    private BoxStore mBoxStore;

    @Override
    public void onCreate() {
        super.onCreate();
        sApp = this;
        mBoxStore = MyObjectBox.builder().androidContext(App.this).build();
    }

    public static App getApp() {
        return sApp;
    }

    public BoxStore getBoxStore() {
        return mBoxStore;
    }
}

CRUD

Now that I have my database setup, I can access it using the BoxStore class. Instead of the typical SQL tables, they have boxes. Here are some example usages of a box:

BoxStore boxStore = App.getApp().getBoxStore();
Box<Animal> animalBox = boxStore.boxFor(Animal.class);

// loads all animals
List<Animal> animals = animalBox.getAll();

// find a specific animal in the database
long myDogId = 12;
Animal myDog = animalBox.get(myDogId);

// insert an animal into the database
animalBox.put(newAnimal);

// update an animal
myDog.setSwimming(true);
animalBox.put(myDog);

//query for all the flying animals
List<Animal> flyingAnimals = animalBox.query().equal(Animal_.isFlying, true).build().find();

//delete all flying animals from the database
animalBox.remove(flyingAnimals);

These are simple examples of the basic CRUD operations. You can do more complex queries too, and without having to write confusing SQL statements. ObjectBox creates queries with a fluent API, so chaining conditions is easy and understandable. To learn more about writing queries, check their documentation.

Relations

Like most other databases, ObjectBox has support for relations. It has support for one-to-one, one-to-many relations and many-to-many relations. Here’s an example of what a one-to-many relation looks like:

@Entity
public class Zoo {

    @Id
    private long id;


    // a Zoo can have many Animals
    @Backlink
    ToMany<Animal> animals;
  
    ...
}

@Entity
public class Animal {
    @Id(assignable = true)
    private long id;

    private String name;

    private boolean flying;

    private boolean swimming;

    private boolean walking;

    // an Animal belongs to one Zoo
    ToOne<Zoo> zoo;
  
    ...
}

This defines a relation between a Zoo, which has many Animals, and the Animal, which belongs to one Zoo. Currently you must make relations at least package private for ObjectBox.

To modify these relations or access them, it looks like this:

Zoo myZoo = new Zoo();

Animal elephant = new Animal();
Animal giraffe = new Animal();

// To-one relation: Set the Zoo that an animal belongs to and save it to the database
elephant.zoo.setTarget(myZoo);
animalBox.put(elephant);

// To-one relation: Get the Zoo that an animal belongs to
Zoo elephantZoo = elephant.zoo.getTarget();


// To-many relation: Add Animals to the Zoo and save it to the database
myZoo.animals.add(elephant);
myZoo.animals.add(giraffe);
zooBox.put(myZoo);

// To-many relation: Get Animals that belongs to a Zoo
List<Animal> zooAnimals = myZoo.animals;

Migrations

Unlike other database libraries (including their own greenDAO), migrations are almost entirely automatic. So you don’t need to worry about managing each schema version.

For example, if you add a new property or delete a property, there’s no migration code required. There are only two cases you need to be concerned with in terms of migration. Renaming a property or class, and changing a property type. They include documenation on how to handle these cases here. In most cases though, there will be no work required for migrations.

Wrap Up

ObjectBox has many more features like transactions, database indexes, Kotlin support, reactive extensions and the list goes on. But, this post should give you a good idea of the approach greenrobot has taken with this library.

At the time of writing this, ObjectBox has just come out of beta with version 1.0. While they are still working on some issues and new features, I think it’s a great library and highly recommend giving it a shot. To learn more about it, you can check out their website here: http://objectbox.io/.

Published on Java Code Geeks with permission by Pierce Zaifman, partner at our JCG program. See the original article here: ObjectBox, a modern and easy to use Android database

Opinions expressed by Java Code Geeks contributors are their own.

Pierce Zaifman

Pierce is a freelance Android app developer and has been developing Android apps for over 4 years. He enjoys learning new technologies and passing that knowledge on to others.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Cyrus
Cyrus
4 years ago

Thank you for sharing the database code is very helpful for me.

https://050williamjames.medium.com/how-to-become-an-android-developer-9c9fa3a4048c

josephsamue
4 years ago

Thank you for explain a database basic function is very helpful for me.

https://josephsamue01.medium.com/how-to-find-the-best-android-app-developer-1694e0edb166

Back to top button