[odb-users] Object not persistent

Boris Kolpackov boris at codesynthesis.com
Wed Jul 6 03:59:10 EDT 2011


Hi Andreas,

Andreas Gerasch <gerasch at informatik.uni-tuebingen.de> writes:

> We now figured out, that links (we use raw pointers) between our objects  
> are not correct in the database, they just point to random numbers.
>
> So, something went wrong during the persist process. Is there something  
> special when using raw pointers?

There is nothing special about using raw pointers but there are some
tricky areas when persisting object references. First of all, all the
objects have to be persisted individually. There is no automatic
persisting of pointed-to objects. So if you have:

#pragma db object
class employer
{
  #pragma db id
  unsigned int id;
};

#pragma db object
class employee
{
  #pragma db id
  unsigned int id;

  employer* er;
};

Then the persist transaction might look like this:

employer er;
er.id = 1;

employee ee;
ee.id = 1;
ee.er = &er;

db->persist (ee);
db->persist (er);

In this particular case it does not matter in which order you persist
the object as long as you have assigned their object ids before calling
persist(). When the persist() function saves the employee object in the
database, it obtains the object id of the employer that is pointed-to
by er. If this object id is not yet initialized, then bad things will
happen, as in this transaction:

employer er;
employee ee;
ee.er = &er;

ee.id = 1;
db->persist (ee); // Bad: ee.er->id is garbage

er.id = 1;
db->persist (er);

The order of the persist () calls becomes important if you are using
automatically-assigned object ids (in the above example we used manually-
assigned ids). In this case, because the id is assigned by the database
during the persist() call, we must serialize the objects in the correct
order, which is pointed-to object (employer) first and pointing object
(employee) second. For example:

#pragma db object
class employer
{
  #pragma db id auto
  unsigned int id;
};

#pragma db object
class employee
{
  #pragma db id auto
  unsigned int id;

  employer* er;
};

employer er;
employee ee;
ee.er = &er;

db->persist (er); // Assigns er.id
db->persist (ee); // Uses ee.er->id

Boris



More information about the odb-users mailing list