Modelling and persistence
What is the object-relational impedance mismatch?
On this page
Objects are often navigated as graphs with references and identity. Relational queries describe sets of rows and their joins. Loading 50 invoices and then following each customer reference can trigger 51 queries. Define the read model and inspect executed queries before choosing eager loading, projection or batching.
Worked example
Pythonimport sqlite3
db = sqlite3.connect(":memory:")
db.executescript('''
CREATE TABLE buyer(id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE invoice(id INTEGER PRIMARY KEY, buyer_id INTEGER);
INSERT INTO buyer VALUES (3, 'Studio');
INSERT INTO invoice VALUES (11, 3), (12, 3);
''')
rows = db.execute(
"SELECT invoice.id, buyer.name FROM invoice "
"JOIN buyer ON buyer.id = invoice.buyer_id ORDER BY invoice.id"
)
assert list(rows) == [(11, "Studio"), (12, "Studio")]
db.close()Explore class relationships in the OOP Playground