Application Development 2

Object-Relational Mapping with Qt

A05 5.11.2019 16:00 - 16:30

Bookmark and Share

Dmitriy Purgin
Dmitriy Purgin

With the increase in the complexity and the amount of data stored in embedded systems, the need in its processing directly on the device increases as well. Modern HMIs should provide the device usage statistics like manufactured pieces, material, fuel or energy consumption, error storage, operating hours, and even personalization settings for multiple users. With the touch panels attached to the device, basic data analysis tools with filtering, sorting and grouping are a natural functional requirement to have, as well as the ability to import and export this data. The use of relational database management systems (DBMS) is the common way to provide data persistence and integrity in a lot of business applications. Qt has the Qt SQL module with the most popular database plugins, and even a built-in support for the SQLite engine which is a light-weight fully functional alternative to the “big” engines like PostgreSQL or MariaDB. However, the relational databases and their query language might be intimidating at first glance. It does not have the same structure as C++, and it works in different paradigm having a set of tables that store primitive data types only. Furthermore, incorporating the database queries directly into the C++ code makes the code inflexible, less testable, adds dependencies to a specific database engine which leads to even more complexity than the good old text files. Object-relational mapping (ORM) is a programming technique intended to overcome these issues. It is a well-known technique to most of the developers in the enterprise world of Java and .NET. OR-Mapper allows to automatically map the data structures expressed in the object-oriented way into their relational table representations in a DBMS-agnostic way. Thus, the software regains the feel natural to a C++ programmer but still benefits from the relational database storage: persistence, consistency, and integrity. The OR-mappers in Java and .NET strongly rely on type introspection and annotation available in these technologies. Thanks to Qt and its Meta-Object System, these approaches can be successfully implemented in C++ as well. The actual implementation of the database layer is based on the Qt SQL module, and uses the standard SQL that allows integration with all the DBMS Qt supports out of the box. Moreover, the database layer is one of the extension points of the proposed OR-mapper, and can be replaced, for example, with a CSV, XML, or NoSQL storage. The talk explains the concepts needed to implement an OR-mapper in Qt, demonstrates a sample implementation and a real-world example. It also covers the comparison to the existing C++ analogues, Java and .NET counterparts.