Johan said:
Hi,
The problem is :
You have a class A with one or more data variables. You want to store the
data variables in a database for example MySQL. Also you do not want to have
SQL code in your class A. Is there a way to translate the Object A to a sql
independed structure. I think it is something with persistent objects or am
I wrong. has anyone experience with this ?
John
What I've done in this situation is implement a container-like class
hierarchy that encapsulates all of the database functionality. For
each class that you want to store in the database you create a new
container class that knows how to translate the database
representation into the C++ representation.
Here's the (very) basic idea:
class Foo { /* a normal class */ };
class Database { /* execute SQL statements using MySQL API */ };
template <typename Type>
class DatabaseSet
{
public :
// implement a persistent container interface
class Iterator;
class ConstIterator;
DatabaseSet& store(); // store objects in database using SQL
DatabaseSet& retrieve(); // retrieve objects from database using
SQL
Iterator insert(const Type& type);
ConstIterator find(const Type& target) const;
Iterator find(const Type& target);
// etc.
virtual ~DatabaseSet();
protected :
DatabaseSet(const Database& database) {} // abstract base class
// generate SQL statements
virtual std::string select_query() const = 0;
virtual std::string insert_query(const Type& type) const = 0;
virtual std::string update_query(const Type& type) const = 0;
private :
SomeContainer<Type> m_container;
Database m_database; // connection to MySQL database
};
class FooSet : public DatabaseSet<Foo>
{
public :
FooSet(const Database& database) : DatabaseSet<Foo>(database) {}
private :
// Foo-specific SQL
virtual std::string select_query() const;
virtual std::string insert_query() const;
virtual std::string update_query() const;
};