Object-Relational Mapping (ORM) is a programming technique used to convert between object models and relational database models. Using ORM in C++ can simplify database operations and improve development efficiency. Although C++ does not have mature ORM frameworks like some dynamic languages, there are still several libraries that can help achieve this goal.
Mainstream ORM Frameworks in C++
Although the C++ ecosystem lacks a “de facto standard” like Java Hibernate, there are several mature or emerging ORM frameworks suitable for different scenarios. The following are the most commonly used ones:
Oat++ ORM (Recommended)
Oat++ is a high-performance C++ Web framework with a built-in lightweight ORM module (oatpp::orm), supporting databases such as SQLite, MySQL, PostgreSQL, etc. Its features include zero dependencies (only requires the C++17 standard library) and high performance (SQL generated via compile-time reflection), making it ideal for scenarios requiring high performance and clean code.
Features:
- Generates SQL at compile time, avoiding runtime reflection overhead.
- Supports complex queries (JOIN, subqueries, aggregate functions).
- Deeply integrated with the Oat++ Web framework (suitable for Web backend development).
Qt ORM (Built into Qt Framework)
Qt is a cross-platform GUI framework, and its built-in Qt ORM (QtSql module) provides object-relational mapping functionality, supporting SQLite, MySQL, PostgreSQL, etc. It is suitable for database operations in Qt GUI applications (such as desktop software).
Features:
- Seamlessly integrated with the Qt ecosystem (signals/slots, model-view).
- Supports visual modeling tools (Qt Creator’s SQL model designer).
- Suitable for small to medium-sized desktop applications.
Poco ORM (Component of Poco Library)
Poco is a general-purpose C++ utility library, and its Poco::Data module provides lightweight ORM functionality, supporting SQLite, MySQL, PostgreSQL, etc. It is suitable for projects that require general utility libraries (such as network services, embedded systems).
Features:
- Lightweight (only depends on the Poco core library).
- Supports flexible query building (chained calls).
- Suitable for projects requiring general data access.
Other Frameworks
- Hibernate C++: A C++ port of Java Hibernate (unofficial), suitable for projects requiring complex ORM functionality (such as enterprise applications).
- SQLPP11: A type-safe SQL building library based on C++11, can be combined with any database (manual object mapping required).
Core Steps for ORM Integration
Using Oat++ ORM as an example (due to its lightweight, high-performance, and zero-dependency nature), we demonstrate the complete process of integrating ORM with C++.
Environment Configuration
Installing Oat++
Download the source code from the Oat++ official website, or install via package managers (such as vcpkg):
vcpkg install oatpp oatpp-sqlite3 # Install Oat++ core library and SQLite driver
Configuring the Compiler
Ensure the compiler supports C++17 and links the Oat++ library. Using g++ as an example:
g++ your_code.cpp -o output -std=c++17 -loatpp -loatpp-sqlite3
Defining Entity Classes (Entity)
Entity classes are the core of ORM mapping and need to declare the mapping relationship with database tables via macros or annotations. Oat++ uses the oatpp::orm::Model macro to define entity classes.
Example: Defining the User Entity Class (corresponding to the users table in the database)
#include "oatpp/orm/Model.hpp"
#include "oatpp/orm/Schema/Migration.hpp"
// Declare database connection (SQLite example)
class Database : public oatpp::orm::Database {
public:
Database(const std::string& connectionString)
: oatpp::orm::Database(connectionString) {}
};
// Define User entity class (mapped to the users table)
class User : public oatpp::orm::Model<User> {
public:
OATPP_DEFINE_MODEL(User,
// Field to table column mapping
OATPP_MODEL_FIELD(Int32, id, "id"), // Primary key (auto-increment)
OATPP_MODEL_FIELD(String, name, "name"), // Name (corresponding to column name)
OATPP_MODEL_FIELD(Int32, age, "age"), // Age (corresponding to column age)
OATPP_MODEL_FIELD(String, email, "email") // Email (corresponding to column email)
);
};
Initializing Database Connection
Create a database connection at program startup and perform migrations (create tables or update table structures).
Example: Initializing the Database
#include "oatpp/orm/Schema/Migration.hpp"
void init_database() {
// Database connection string (SQLite example: file path)
std::string db_path = "test.db";
auto db = std::make_shared<Database>("sqlite://" + db_path);
// Perform migration (create users table)
oatpp::orm::Schema::Migration::createTableIfNotExists<User>(*db);
}
Performing CRUD Operations
Operate entity classes through the Repository (warehouse) class provided by ORM to implement create, read, update, and delete operations.
Create
void create_user(oatpp::orm::Database& db) {
// Get User repository
auto user_repo = db.getRepository<User>();
// Create User object
auto user = User::createObject();
user->name = "Zhang San";
user->age = 25;
user->email = "zhangsan@example.com";
// Insert into database (automatically generates SQL: INSERT INTO users (name, age, email) VALUES (?, ?, ?))
user_repo->create(user);
}
Read
void query_users(oatpp::orm::Database& db) {
auto user_repo = db.getRepository<User>();
// Query all users (automatically generates SQL: SELECT id, name, age, email FROM users)
auto users = user_repo->findAll();
// Iterate through results
for (const auto& user : users) {
std::cout << "User: " << user->name
<< "(ID:" << user->id
<< ", Age:" << user->age
<< ", Email:" << user->email << ")" << std::endl;
}
}
Update
void update_user(oatpp::orm::Database& db, int user_id) {
auto user_repo = db.getRepository<User>();
// Query the user to update
auto user = user_repo->findOneById(user_id);
if (user) {
user->age = 26; // Modify age
user_repo->update(user); // Generates SQL: UPDATE users SET age=? WHERE id=?
}
}
Delete
void delete_user(oatpp::orm::Database& db, int user_id) {
auto user_repo = db.getRepository<User>();
// Delete user (generates SQL: DELETE FROM users WHERE id=?)
user_repo->eraseById(user_id);
}
Transaction Management
ORM supports transactions to ensure the atomicity of a group of operations (either all succeed or all roll back).
Example: Transfer Transaction
void transfer_money(oatpp::orm::Database& db, int from_id, int to_id, int amount) {
// Start transaction (auto-commit disabled)
db.begin();
try {
auto user_from_repo = db.getRepository<User>();
auto user_to_repo = db.getRepository<User>();
// Deduct balance from source account
auto user_from = user_from_repo->findOneById(from_id);
if (!user_from || user_from->age < amount) { // Assume age is balance (example)
throw std::runtime_error("Insufficient balance in source account");
}
user_from->age -= amount;
user_from_repo->update(user_from);
// Add balance to destination account
auto user_to = user_to_repo->findOneById(to_id);
if (!user_to) {
throw std::runtime_error("Destination account does not exist");
}
user_to->age += amount;
user_to_repo->update(user_to);
// Commit transaction
db.commit();
std::cout << "Transfer successful, amount: " << amount << std::endl;
} catch (const std::exception& e) {
// Roll back transaction
db.rollback();
std::cerr << "Transfer failed, rolled back: " << e.what() << std::endl;
}
}
Advantages and Limitations of ORM
Advantages
- Reduces repetitive code: Automatically generates SQL, avoiding manual writing of
INSERT,SELECT, etc. - Type safety: Entity class fields are bound to database column types (e.g.,
Int32corresponds toINTEGER), with compile-time type checking. - Maintainability: Object-oriented operations align with object-oriented design, resulting in clear code structure.
- Cross-database support: ORM frameworks encapsulate differences between databases (e.g., SQLite’s
AUTOINCREMENTvs. MySQL’sAUTO_INCREMENT).
Limitations
- Performance overhead: Compile-time reflection or runtime metadata processing may introduce additional overhead (use with caution in high-performance scenarios).
- Complex query limitations: ORM support for complex SQL (such as multi-level nested subqueries, stored procedures) may not be as flexible as native SQL.
- Learning cost: Requires familiarity with the specific syntax of the ORM framework (such as Oat++’s
OATPP_MODEL_FIELDmacro).
Choosing an ORM Library
Currently, there are several well-known ORM libraries in the C++ community, such as:
- Soci
- CppCMS
- Odb
- Sqlpp11
Here, we introduce Soci and Odb as examples.
Soci Library
Soci is a lightweight C++ ORM library that supports multiple databases.
Installing Soci
# Debian/Ubuntu
sudo apt-get install libboost-all-dev libmysqlclient-dev
git clone https://github.com/SOCI/soci.git
cd soci
mkdir build
cd build
cmake ..
make
sudo make install
Usage Example
#include <soci/soci.h>
#include <soci/mysql/soci-mysql.h>
using namespace soci;
int main() {
session sql(soci::mysql, "dbname=test user=root password=root host=localhost");
// Insert data
sql << "INSERT INTO users (name, age) VALUES (:name, :age)",
use("John Doe"), use(30);
// Query data
std::string name;
int age;
sql << "SELECT name, age FROM users WHERE name = :name",
into(name), into(age),
use("John Doe");
std::cout << "Name: " << name << ", Age: " << age << std::endl;
return 0;
}
Odb Library
Odb is a powerful C++ ORM library that supports multiple databases.
Installing Odb
# Debian/Ubuntu
sudo apt-get install libodb-dev libodb-mysql-dev
Usage Example First, define a class and use Odb’s preprocessor to generate the corresponding database mapping file.
// user.h
#include <odb/core.hxx>
#include <odb/mysql/mysql.hxx>
struct User
{
int id;
std::string name;
int age;
template<unsigned N>
void trigger()
{
}
template<unsigned N>
void load(const unsigned char*&, const unsigned char*)
{
}
};
ODB_DEFINE_PERSISTENT(User, mysql)
ODB_PERSISTENT_FIELD(User, id)
ODB_PERSISTENT_FIELD(User, name)
ODB_PERSISTENT_FIELD(User, age)
ODB_KEY_FIELD(User, id)
Then write the main program to use this class.
#include "user.h"
#include <odb/session.hxx>
#include <odb/mysql/mysql-session.hxx>
using namespace odb;
int main() {
mysql::database db("dbname=test user=root password=root host=localhost");
// Insert data
User user;
user.name = "Jane Doe";
user.age = 25;
transaction t(db.begin());
db.insert(user);
t.commit();
// Query data
transaction t2(db.begin());
User user2;
db.load(user2, 1); // Assume id is 1 after insertion
t2.commit();
std::cout << "Name: " << user2.name << ", Age: " << user2.age << std::endl;
return 0;
}
SQLpp11 Library
SQLpp11 is a modern C++ SQL library. It is not a traditional ORM, but it provides ORM-like functionality.
Installing SQLpp11
# Debian/Ubuntu
sudo apt-get install libsqlite3-dev
git clone https://github.com/rbock/sqlpp11.git
git clone https://github.com/rbock/sqlpp11-connector-sqlite3.git
Usage Example
#include <sqlpp11/sqlpp11.h>
#include <sqlpp11/sqlite3/sqlite3.h>
using namespace sqlpp11;
using namespace sqlpp11::sqlite3;
struct Users {
int id;
std::string name;
int age;
};
int main() {
auto db = connect_to_sqlite3(":memory:");
create_table_if_not_exists(db, Users{});
insert_into(db, Users{})
.set(Users{}.name = "John Doe", Users{}.age = 30)
.execute();
auto result = select(Users{}.name, Users{}.age)
.from(Users{})
.where(Users{}.name == "John Doe")
.execute(db);
for (const auto& row : result) {
std::cout << "Name: " << row.name << ", Age: " << row.age << std::endl;
}
return 0;
}



