[odb-users] Composite object id with a to-many relationship

Romain Gros grosr.romain at gmail.com
Thu Nov 14 12:03:28 EST 2013


Hi !

I have been working on a problem for a little while and I can't find the
answer to that.

Here's the thing:
I have a class, ObjectInstance, with a vector of ObjectSpecification.

Here are the definitions of the classes:
/// ObjectInstance.hxx

# pragma db object
class ObjectInstance {
public:
typedef std::vector<odb::lazy_weak_ptr<ObjectSpecification>
> ObjectSpecificationType;

private:
# pragma db id auto
   int   _idobjectinstance;

# pragma db value_not_null inverse(_instance)
ObjectSpecificationType _specifications;

/** getter/setter, etc. **/
};

/// ObjectSpecification.hxx

# pragma db value
class ObjectSpecificationId {
private:
int _idinstance;
int _idspecification;
};

# pragma db object
class ObjectSpecification {
private:
# pragma db id column("")
ObjectSpecificationId _idobjectspecification;
int _value;

# pragma db not_null column("idinstance")
std::shared_ptr<ObjectInstance> _instance;

/** getter/setter, etc. **/
};

Basically, what I wanted to have, is the following mechanism: my
ObjectInstance has multiple ObjectSpecification. We know that the
ObjectSpecification is related to an ObjectInstance because the
ObjectSpecificationId::_idinstance is equal to ObjectInstance::_idinstance.
That's what I want for the load of an ObjectInstance.

The fact is that I cannot specify, in the inverse pragma member, something
like that: inverse(_idobjectspecification._idinstance), which would be
perfect for me.

To simulate the fact that we can access the
ObjectSpecificationId::_idinstance, I use a reference to the ObjectInstance
in the ObjectSpecification (as shown above).
The thing work well for the load, but with that, I cannot insert new
ObjectSpecification, because the persist_statement generated defines two
times the idinstance and cause an MySQL error:
"INSERT INTO `ObjectSpecification` "
  "(`idinstance`, "
  "`idspecification`, "
  "`value`, "
  "`idinstance`) "
  "VALUES "
  "(?, ?, ?, ?)";

Do you know a good way to do that ? Did I miss something with the composite
object ids that would allow me to do what I want ?
Also, a solution that I didn't try yet is the use of the post_load
callback, but if I do that, I'm afraid that I won't be able to use
lazy_ptr, right ?

Thanks a lot,
Romain


More information about the odb-users mailing list