issue with Wt::Dbo::collection
Added by Stefano Manni about 13 years ago
Hi everyone,
I have a trouble with a method that returns a collection of dbo pointer.
here the method:
/** userManager.C **/
Wt::Dbo::collection< Wt::Dbo::ptr<User> > fetchAllUsers() const {
Wt::Dbo::Transaction transaction(session);
Wt::Dbo::collection< Wt::Dbo::ptr<User> > users;
try {
users = session.find<User>();
transaction.commit();
Logger::instance()->log(Logger::DEBUG, "Successfully fetched all users.");
}
catch (Wt::Dbo::Exception& e) {
users = Wt::Dbo::collection< Wt::Dbo::ptr<User> >();
transaction.rollback();
Logger::instance()->log(Logger::WARNING, "Unable to fetch all users. Generic error.");
}
return users;
}
here the main that uses the method above:
/** main.C **/
Wt::Dbo::collection< Wt::Dbo::ptr<User> > users = UserManager::instance(session)->fetchAllUsers();
std::cout<< "#users: " <<users.size()<<"\n";
for (Wt::Dbo::collection< Wt::Dbo::ptr<User> >::iterator i = users.begin(); i != users.end(); ++i)
std::cerr << "user " << (*i)->name << "\n";
and here the output:
/** output **/
#users: 55
terminate called after throwing an instance of 'Wt::Dbo::Exception'
what(): Dbo load(): no active transaction
The program has unexpectedly finished.
Any ideas?
Thanks in advance
Replies (3)
RE: issue with Wt::Dbo::collection - Added by Stefano Manni about 13 years ago
Ok I fixed it. Code that does the 'find' does not have to do the commit/roolback:
/** userManager.C **/
Wt::Dbo::collection< Wt::Dbo::ptr<User> > fetchAllUsers() const {
Wt::Dbo::Transaction transaction(session);
Wt::Dbo::collection< Wt::Dbo::ptr<User> > users;
try {
users = session.find<User>();
/**** transaction.commit(); ****/
Logger::instance()->log(Logger::DEBUG, "Successfully fetched all users.");
}
catch (Wt::Dbo::Exception& e) {
users = Wt::Dbo::collection< Wt::Dbo::ptr<User> >();
/**** transaction.rollback(); ****/
Logger::instance()->log(Logger::WARNING, "Unable to fetch all users. Generic error.");
}
return users;
}
Can anyone confirm that the transaction.commit() is necessary only when a new object has to be inserted or an existing one has to be updated?
tnx
RE: issue with Wt::Dbo::collection - Added by Koen Deforche about 13 years ago
Hey,
Indeed, you need a transaction to iterate the results in a collection.
Regards,
Koen
RE: issue with Wt::Dbo::collection - Added by Stefano Manni about 13 years ago
you are right! I solved it