Beginner C++ Database Tutorial: How to use ObjectBox

Beginner C++ Database Tutorial: How to use ObjectBox

Introduction

As a direct follow up from the ObjectBox database installation tutorial, today we’ll code a simple C++ example app to show how the database can be used. Before starting to program, let’s briefly overview what we want to achieve with this tutorial and what is the best way to work through it.

Overview of the app we want to build

In short, we will make a console calculator app with an option to save results into memory. These will be stored as objects of the Number class. Every Number will also have an ID for easy reference in future calculations. Apart from the function to make calculations, we will create a function to enter memory. It will list all the database entries and have an option to clear memory. By coding all of this, we will make use of such standard ObjectBox operations as put, get, getAll and removeAll.

Our program will consist of seven files: 

  • the FlatBuffers schema file, that defines the model of a class we want to store in the database
  • the header file, for class function definitions
  • the source file, for function implementation
  • the four files with objectbox binding code that will be created by objectbox-generator

How to use this tutorial

While looking at coding examples is useful in many cases, the best way to learn such a practical skill like programming is to solve problems independently. This is why we included an exercise for each step. You are encouraged to make the effort and do each of them, even if you don’t know the answer straight away. Only move to the next step after you test each part of your program and make sure that everything works as intended. Ideally, you should only use the code snippets presented here to check yourself or look for hints when you feel stuck. Bear in mind that sometimes there might be several different ways to achieve the same results. So if something that we ask you to do in this tutorial doesn’t work for you, try to come up with your own solution.

How to create the FlatBuffers file?

First, we’ll create the FlatBuffers schema (.fbs) for our app. This is required for the objectbox-generator to generate binding code that will allow us to use the ObjectBox library in our project. 

The FlatBuffers schema consists of a table, which defines the object we want to store in the database, and the properties of this object. Each property consists of a name and a type. We want to keep our example very simple, so just two properties is enough.

  1. To replicate a calculator’s memory, we want ObjectBox to store some numbers. We can define the Number object by giving the table a corresponding name.
  2. Inside the table, we want to have two properties: id and contents. The contents of each Number object is the number itself (double), while id is an ulong that our program will assign to each of them for easy identification.

Exercise: create a file called numbers.fbs and define the table in the format

Reveal code

Generating binding code

Now that the FlatBuffers file is ready, we can generate the binding code. To do this, run the objectbox-generator for our FlatBuffers file:

The following files will be generated:

  • objectbox-model.h
  • objectbox-model.json
  • numbers.obx.hpp
  • numbers.obx.cpp

The header file

This is where the main chunk of our code will be. It will contain the Calculator class and all the function definitions.

  1. Start by including the three ObjectBox header files: objectbox.hpp, objectbox-model.h and numbers.obx.hpp. Our whole program will be based on one class, called Calculator. It should only have two private members: Store and Box. Store is a reference to the database and will manage Boxes. Each Box stores objects of a particular class. In this example, we only need one Box. Let’s call it numberBox, as it will store Numbers that we want to save in the memory of our calculator.

Exercise: create a file called calculator.hpp and define the Calculator class with two private members: reference to the obx library member Store and a Box of Numbers.

Reveal code

2. After the constructor, we define the run function. It will be responsible for the menu of our program. There should be two main options: to perform calculations and enter memory. As discussed above, we want this app to do two things: perform calculations and show memory. We’ll define these as separate functions, called Calculate and Memory. The first one is quite standard, so we won’t go into a detailed explanation here. The only thing you should keep in mind is that we need to account for the case when the user wants to  operate on a memory item. To deal with this, we’ll process input in a function called processInput.

Exercise: define the parametrised constructor which takes a reference to Store as a parameter. Then define the run and Calculate functions.

Reveal code

3. The final part of this function is for saving results into memory. We start by asking the user if they want to do that. If the answer is positive, we create a new instance of Number and set the most recent result as a value of its contents. To save our object in the database, we can operate with put(object) on our Box. put is one of the standard ObjectBox operations, which is used for creating new objects and overwriting existing ones. 

Exercise: create an option to store the result in memory, making use of the ObjectBox put operation.

Reveal code

4. Next, we should define processInput, which will read input as a string and check whether it has the right format. Now, to make it recognise the memory items, we have to come up with a standard format for these. Remember, we defined an ID property for our Numbers. Every number in our database has an ID, so we can refer to them as, e.g. m1, m2, m3 etc. To read the numbers from memory, we can make use of the get(obx_id) operation. It returns a unique pointer to the corresponding Number, whose contents we need to access and use as our operand.

Exercise: define the processInput function, which detects when something like m1 was used as an operand and updates x, y, and op according to the input.

Reveal code

5. The last function in our header file will be Memory. It should list all the numbers contained in the database and have an option to clear data. We can read all the database entries by calling the getAll ObjectBox operator. It returns a vector of unique pointers. To clear memory, you can simply operate with removeAll on our Box.

Exercise: define the Memory function, which lists all the memory items, and can delete all of them by request.

Reveal code

The source file

To tie everything together, we create a source (.cpp) file. It should contain only the main function that initialises the objectbox model, creates an instance of the Calculator app, and runs it. To create the ObjectBox model, use

then passing options as a parameter when you initialise the Store.

Exercise: create the source file

Reveal code

Final notes

Now you can finally compile and run your application. At this point, a good exercise would be to try and add some more functionality to this project. Check out the ObjectBox C++ documentation to learn more about the available operations.

After you’ve mastered ObjectBox DB, why not try ObjectBox Sync? Here is another tutorial from us, showing how easily you can sync between different instances of your cross platform app.

Other than that, if you spot any errors in this tutorial or if anything is unclear, please come back to us. We are happy to hear your thoughts.

Startup Sesame –  a field report

Startup Sesame – a field report

What is Startup Sesame?

Startup Sesame is a one-of-a-kind program that connects European founders to European event organizers, bringing startups to amazing events throughout the year. While the exposure to events is great on its own, what’s even better is the network, on-site intros and especially the team behind it: Ben Costantin and his crew (@startupsesame).

Why Startup Sesame?

As a startup, you usually cannot afford to go to many conferences; however, a well-planned event can give you media exposure, great connections, sales leads, new ideas and generally provides you with learning opportunities along the value creation chain of your startup (from customer experience, networking, to closing a deal). It also gives you a great “reason for reaching out”. Yet, filtering out tons of events and which to attend, researching and planning the event in advance, and then performing on site and catching up with everything afterwards is a lot of work. Having a partner like Startup Sesame that helps you navigate that jungle, getting in touch with people on site, and last but not least with the financial costs, is invaluable. Even more, Startup Sesame not only sponsors most event tickets, they also provide additional opportunities to make use of the occasion like e.g. competing in the pitching competition, having a booth.

How does Startup Sesame work?

First of all, you need to apply.

Then, if you are selected, you are invited to a starting weekend where you get to meet

Startup Sesame

Startup Sesame

Startup Sesame weekend 2018 (photo by Kara Ferguson)

Then during the weekend, you get educated about the current startup ecosystem, the events, trends and most importantly the opportunity to pitch and get feedback on your pitch.

Startup Sesame

Startup Sesame

 

Panel discussion at the Sesame Summit 2018

This weekend allows the Sesame team and the startup organizers to get to know you and your business. This way, they can learn how to best help you and make unique recommendations on events and competitions to apply to. It also gives you the opportunity to understand what VCs and event organizers are looking for in startup competitions and on-stage talks, which events make sense for you, and how to go about these opportunities to really make use of them for the business. It also helps you refine your pitch.

After the weekend, you receive additional feedback and mentoring and then, during the following year you are presented (actively!) with event opportunities that match your startup and personality. Also, they assign #rockstar #mentors to you that help you make the most out of your event attention on site.

 

Startup Sesame Cohorte Retreat

Every year is organized differently. In our 2018 cohorte the setting was special: We were spending the time all together in shared rooms in a youth hostel at the Valencian beach. Food and coffee was a bit restricted, so we all needed to share and pay attention to each other’s needs. This brought the cohorte closer together than I think would usually have been the case (also great for the more introvert people… :D).

Who is Ben?

Ben is the founder and leader of Startup Sesame. Ben’s superpower is connecting people, or rather the right people; people who can benefit from being connected. Ben has a big heart, is very kind, and I believe he truly enjoys helping founders — and this really is what shapes the spirit of Startup Sesame. I am grateful to be part of the Startup Sesame Family (#proudsesamer).

Is it worthwhile?

For ObjectBox the answer is Yes. Once the next applications open I can only encourage you to apply. Just one word of warning: They give you tons of opportunities and in all likelihood, you can’t handle them all. E.g.: We needed to be very selective due to time constraints and it was/is hard to see many great opportunities pass by unused. However, you can check out what the #proudsesamer of 2018 have achieved in the last months on @startupsesame — it’s impressive and entertaining. ?

These are the kind of events that you can attend as part of Startup Sesame. It was a great experience and lots of fun, but also added great value to our fundraising.

Or, if you are at dmexco 2018 or SaaStock 2018, you can join my talk on Open Source and Edge Computing. We can meet up there too 🙂

Let’s dive into the iOS World

Let’s dive into the iOS World

Two days ago, we attended the Swift Lighting Talks Meetup in Munich for the very first time. We had beer, pizza and listened to Sebastian Sellmeier’s presentation on making programming accessible and Denis Grebennicov’s presentation on the process of developing a Document Scanner app. It was fun and very instructive, thanks!

We also gave a 15 minute sneak peek talk about our ObjectBox iOS binding. Markus covered the basics of ObjectBox before sharing how we managed to overcome iOS constraints in our APIs. Finally, he disclosed the first (early) performance benchmarks on iOS, which we think are quite encouraging…

Check out the full talk in the video below.

In case you want to learn more about ObjectBox on iOS, sign up here for news and Early Access.
Special thanks to Stefan Mayer-PoppThe Munich iOS Developers Meetup for organizing this event and to Mayflower for hosting it.

 

We officially released our YouTube channel, we will post videos about ObjectBox and Tech in general. Subscribe to stay tuned.

 

ObjectBox 1.0

ObjectBox 1.0

ObjectBox 1.0 is a SQLite database replacement. It makes object persistence on mobile (and IoT) devices simple and fast.

Code actually tells best what ObjectBox does (yes, it also does Kotlin):

Don’t get us wrong: we think SQLite is a great piece of software and SQL is really powerful. We just do not love touching SQL so much when developing apps. That’s why we developed a very fast and easy alternative.

Being lazy or eager? Relations

ObjectBox comes with strong support for relations. How do you store a new object along with referenced objects? It’s simple:

Thus, with a single put(playlist), ObjectBox will not only persist the Playlist object but also the two associated Song objects. This also works with objects that were already persisted in the database.

A common challenge with relations is that they are typically loaded lazily. This can cause brief delays when accessing a relation for the first time, because the data must be pulled from the database at that moment. This in turn can cause the UI to slow down, e.g. when scrolling through the list (known as the “N+1 query problem”). Obviously, this may be harmful to the user experience and thus something you try to avoid. That is one of the reasons some ORMs do not support relations at all.

ObjectBox solves this challenge by enabling queries to preload relations in the background – aka “eager loading”. This makes processing the query result in the main thread super fast. Once the query is processed, eagerly loaded relations do not touch the database at all.

Eager loading is part of the Query API and not the entity itself. This gives you full flexibility over when to load what. For each query, you can specify which relations to preload like this:

POJOs

We want to keep things simple. The objects returned from ObjectBox are POJOs (plain old Java objects). When you get an object, all properties are initialized and ObjectBox will never change the values. And, of course, you can pass those objects around in different threads.

Let’s also have quick look on entity classes. First, ObjectBox does not enforce a specific base class. You are free to extend from any class. Second, the classes also define the data model in the database (the “database schema”). Adding and removing entities/properties just work. Only renames require your interaction. The days of CREATE TABLE scripts are finally gone, and typical data model updates do not require migration scripts.

Fast

We keep saying ObjectBox is fast. But how fast? And for what? We put together an open source benchmarking app, which come with a couple of performance tests for CRUD, queries, etc. Please check it out, have a look at the code, and make up your mind on the performance of ObjectBox. We really want to provide fair benchmarks.

Thank you!

A big thank you goes out to everyone who helped us in our beta phase (e.g. reported GitHub issues, blogs, …). It was only with your help that we reached version 1.0 now! As a special sign of appreciation, we’ll send out exclusive “early adopter” ObjectBox T-shirt: just write to us (contact@… – our domain) by September, 15th, with a link to your contribution along with your size and address.

We will add each and everyone that supports us and is part of the ObjectBox journey on our About us page! ObjectBox really is about you. So, let us know how you contributed (small things sometimes matter most…) and send us your picture and link (e.g. to your GitHub Account, Website or LinkedIn page).

Roadmap: bring your app to the edge

Our vision for ObjectBox is edge computing. It brings the data back to the user, to the device in his hand or home. We believe this is the future of computing. Small devices are tremendously powerful now, and it’s time to claim independence from the cloud while keeping in touch.

Before we go all edgy, we will address some essentials: Our plan for Version 1.1 is to rework the query API to and make expose object link API (aka “joins”). We also have to do our homework with some corner cases for data model changes. And of course, you may still find rough edges with the 1.0, which we’ll get rid off as soon as possible. We are dedicated to make ObjectBox a pure pleasure to work with.

We’re continually looking for feedback. Please do let us know what you think about ObjectBox: either by writing us at contact@… (our domain), or by answering these quick questions. Thank you!

ObjectBox 0.9.10 – getting closer to 1.0

ObjectBox 0.9.10 – getting closer to 1.0

ObjectBox 0.9.10 - getting closer to 1.0

Do you know our new super fast mobile database ObjectBox yet? With versions 0.9.9 and the just released 0.9.10, ObjectBox made great progress to stabilize features for the 1.0 release. With an increasing number of apps using ObjectBox, we were able to spot and fix some less obvious issues. We believe that ObjectBox 0.9.10 is the most stable release ever. If you did not dare to check out the beta version yet: now is a good time to have a closer look.

(more…)