[odb-users] ODB Session

Boris Kolpackov boris at codesynthesis.com
Tue Aug 27 06:58:25 EDT 2013

Hi Alessandro,

Alessandro Bellina <abellina at gmail.com> writes:

> Does odb::session provide benefit if one must re-query for the object(s)
> over and over? (i.e. if the object id is not known ahead of time..)

Here is what happens during a query:

1. The query is executed on the database server and the state of
   matching objects is returned to the application (either all at
   once or streaming, depending on the query result caching policy).

2. When you iterate over the query result, ODB takes this state
   and instantiates actual C++ object with it. If session is
   present, before doing this instantiation, ODB check the
   session's object cache if this object has already been
   loaded. If so, then it is returned instead.

The important point to your question is that the state of the
matching objects is returned to the application regardless of
whether the object is cached or not (we need to know which
objects match the query condition before we can know whether
they are cached).

So, to answer your question, session won't provide a significant
benefit for simple objects. That is, objects that don't contain
any (eager) object pointers or containers. For objects that do
contain any of these parts (which require additional database
statements to load), session will provide a potentially
significant benefit.

Also, if you know that most of the objects returned by your
query will be cached in the session, then your can instead
create a view that returns just object ids and then load
the object (presumably from the cache). For example:

#prgama db object
class person

  #pragma db id
  unsigned long id;

// Old way:
typedef odb::query<person> query;
typedef odb::result<person> result;

result r (db.query<person> (query::age > 18));

for (result::iterator i (r.begin ()); i != r.end (); ++i)
  person& p (*i);

// New way:
#prgama db view object(person)
class person_ids
  unsigned long id;

typedef odb::query<person_ids> query;
typedef odb::result<person_ids> result;

session s;

result r (db.query<person_ids> (query::age > 18));

for (result::iterator i (r.begin ()); i != r.end (); ++i)
  auto_ptr<person> p (db.load<person> (i->id)); // In most cases comes from s.


More information about the odb-users mailing list