[odb-users] Problem with updating a transient object when adding a ptr in a to-many relationship

Chris Visser chris at cwmmarketing.co.za
Mon Feb 22 01:37:51 EST 2016


Hi

 

In the source code below I always get the exception thrown. I have tried
several ways of doing it, and still I get an error. I tried the following
methods:

 

1.       As below, where I create the Address as a shared_ptr, persist, add
to Person and update Person

2.       Create the Address Object, persist, add to Person and update Person

3.       Create Address as shared_ptr, add to Person and update Person.

4.       Create Address as lazy_shared_ptr, persist (not persist), add to
Person and update Person

5.       Create address, persist, load again from DB as a shared_ptr or
lazy_shared_ptr, add to Person and update Person.

 

I have tried all combinations I can think of, and I always end up with the
exception being thrown. What am I doing wrong here?

 

NOTE: The below code is a fragment of what I really have. In reality the
Person class has several vectors and shared_ptr's. But I only add one single
element to one single vector. And then I get the error. Some of the class
members are lazy_shared_ptr and it is not a good idea to actually load that
ptr since it will incur a huge performance hit as well as memory drain.
Think of it as a company, with a vector of employees, each having multiple
address, phone numbers, projects, etc. But the principle of what I want to
achieve is shown below.

 

Please tell me what I am doing wrong here.

 

 

Thanks

 

 

Chris

 

 

 

#pragma db object

Class Person{

public:

                friend class odb::access;

#pragma db id auto

                int m_Id;

                odb::vector<odb::laze_shared_ptr<Address>> m_Addresses;

}

 

#pragma db object

class Address {

public:

                friend class odb::access;

#pragma db id auto

                int m_Id;

                std::string m_AdddressLines;

}

 

int main()

{

                std::shared_ptr<odb::database> db = ...

                typedef odb::query<Person> PersonQuery;

                typedef odb::result<Person> PersonResult;

 

                try{

                odb::transaction t(db->begin);

                std::shared_ptr<Person> john =
db->query_one<Person>(PersonQuery::Id = 1);

                std::shared_ptr<Address> address(new Address());

                Address->m_AddressLines = "Address of the person";

                int addressId = db->persist(address);

                john->m_Addresses->push_back(address);

                db->update(john);

                t.commit();

                }

                catch (odb::object_already_persisted& e)

                {

                                std::cout << "Error: " << e.what() <<
std::endl;

                                return 1;

                }

return 0;

}



More information about the odb-users mailing list