[odb-users] Is there a way to persist an object to a specific table?

Boris Kolpackov boris at codesynthesis.com
Fri Oct 28 09:28:14 EDT 2011


Hi Narayanan,

SS Narayanan <nara at bvinetworks.com> writes:

> I wanted to learn if there is a way to persist and object to a specific
> table instead of the name of the table as the name of the object. For
> example, if I have a class named person, I will do something similar to the
> following: 
> 
> person john("John", "Doe", 33);
> 
> transaction t (db->begin());
> 
> db->persist(john);
> 
> t.commit();
> 
> The record is added to the table "person" in the DB. What is the way to add
> the person record to another table, say "MyPerson"? And how do I create the
> new table programmatically.

I see three ways to interpret your question:

1. If you need to change the name of the table in which the person objects
   are stored, then this one is easy. You simply use the table pragma, for
   example:

   #pragma db object table("MyPerson")
   class person
   {
     ...
   };

   The MyPerson table will be created automatically.

2. If you have a few tables where you may need to store the person objects
   and the names of these tables are known at compile time, then this is
   a bit more complex. You can do it by creating a persistent class for
   each table. To avoid duplicating the code, you can factor all the data
   members to out to the abstract base class. For example:

   #pragma db object abstract
   class person
   {
     ...
   };

   #pragma db object table("MyPerson")
   class my_person: public person
   {
   };
   
   #pragma db object table("YourPerson")
   class your_person: public person
   {
   };

   The MyPerson and YourPerson tables will be created automatically.

3. Finally, if you only know the names of the tables where you need to
   store the person objects at run-time, then there is currently no way
   to handle this case in ODB. The names of the tables are embedded in
   the statements generated for each persistent class and the statements
   themselves are prepared and cached. Providing a table name at run-
   time would make it a lot less efficient.

   The only workaround for this case that I can think of would be to 
   dynamically create a table alias using a native SQL statement. As
   far as I know, only DB/2 provides something like this (see CREATE
   ALIAS).

Boris



More information about the odb-users mailing list