I currently keep a list of objects, and these objects contain data. I want to move that data into an SQLite relational database and have my objects access it using SQL, but i am not sure how to map the rows in a table to objects in my application.
It's not like i am reading data from the database and storing it in my objects, my objects will just be like shells and they will access the data directly from the database (which is in memory).
One way would be to keep a list of objects in my application and keep a table in the db. I would use an id as the primary key in the DB and that id is the index of the corresponding object in the list. But i'm not sure if that's the best way to do it. Perhaps Qt provides a better mechanism (QSqlRecord perhaps?).
I also don't know how to store references to other objects. Say my object model looks like this:
class ObjectA { int id; int otherData; ObjectB anObject;};class ObjectB { int id; int otherData;};
Then i would define an SQL table like so:
create table ObjectA( id int primary key, otherData int; /*ObjectB ??? */);create table ObjectB( id int primary key, otherData int;);
And i have a list of ObjectA objects. I could store ObjectB in the DB as a separate table, but how would i have each ObjectA reference an ObjectB?
Another thing i am concerned about is speed. Although speed is not a critical factor in my application, i do want it to be fairly fast and efficient. So i was wondering if accessing data in a DB via SQL statements would be noticeably slower than accessing data stored in the object itself.
When i want to access some data in bulk (say, get all x variable of each object in my list), I would think that a single SQL statement would be the faster than iterating over each object and have it execute a separate statement.
i.e.
QSqlQuery query(database);query.exec("select otherData from ObjectA");while (query.next()) { doSomething(query.value(0));}
Would be more efficent than
for each ObjectA in list { QSqlQuery query(database); query.exec("select otherData from ObjectA where id = " + each.id); doSomething(query.value(0));}
But how would i do the first example in an object-oriented way? That is, i do not want to go accessing the DB directly everywhere, i want to use my object model.