Introduction to C + + ORM ODB

Source: Internet
Author: User
Tags data structures unique id

1.ORM



ORM, Object Relational Mapping, is used to map object-based data structures to the SQL structure. The object-based data is mapped to fields in the relational table, and then we can manipulate the database through the interface provided by the object, without having to write the SQL statement to manipulate the database.
Typically a relational table corresponds to two classes, an entity class, and an action class.
ORM is a framework, not an implementation.


The implementation of 2.c++ ORM ODB

1) A simple example
#include <odb/core.hxx>//(1)


#pragma db object//(2)


Class Person
{
Public
Person (const std::string& First,
Const std::string& Last,
unsigned short age);
Const std::string& First () const;
Const std::string& last () const;
unsigned short age () const;
void age (unsigned short);
Private
Person (); (3)

Friend Class odb::access;//(4)

#pragma db ID auto//(5)
unsigned long id_;//(5)
Std::string First_;
Std::string Email_;
Std::string Last_;
unsigned short age_;
};


Note:
(1) headers to provide class like ' access '


(2) Tell the compiler that this is a persistent class, so we're going to put #pragma db object before the definition of the class. Declaring a class as persistent class does not mean that all objects of this class will be stored in the database.


(3) This constructor is used when instantiating a persistent class.


(4) Enable the default constructors and other class members to access the Access class.


(5) Each persistent object usually has a unique ID. If the persistent object does not have an ID defined, the operation of the database is limited.
#pragma db ID auto is used to specify this object Id,auto indicates that the value of this ID is automatically assigned by the database.
This ID allows the class to have its own members, or it can add itself as an ID to identify different persistent objects. The id_ in the above example is used only to distinguish persistent object.


We can also write the above example:
#include <odb/core.hxx>//(1)


#pragma db object//(2)
Class Person
{
Public
Person ();
Person (const std::string& First,
Const std::string& Last,
unsigned short age);
Const std::string& First () const;
Const std::string& last () const;
unsigned short age () const;
void age (unsigned short);
Private
#pragma db ID auto//(5)
unsigned long id_;//(5)
Std::string First_;
Std::string Email_;
Std::string Last_;
unsigned short age_;
};
The ID used to specify the persistent
#pragma db object (person)
#pragma DB Member (PERSON::EMAIL_) ID


3. Generate code with the ODB compiler

Save the above code as PERSON.HXX and compile it using the following command:
odb-d MySQL--generate-query person.hxx
-D is used to specify the database that we use. ODB supports many different databases, let's take MySQL for example.


This command causes the ODB compiler to generate three files: person-odb.hxx, Person-odb.ixx, Person-odb.cxx.


The--generate-query is used to specify the code that the compiler generates for database support. If we use--generate-shema, the Person-odb.sql file will also be generated.


OK, now we have persistent class (PERSON.CXX) and database support code (PERSON-ODB.HXX, Person-odb.ixx, Person-odb.cxx).


4. Compiling and Running

If our main file is Diver.cxx, we should first compile the main file and the Cxx file generated above:
C + + C Driver.cxx
C + + C Person-odb.cxx-iyou_dir_to_odb_headers
C + O driver driver.o person-odb.o-lyou_dir_to_odb_lib


Before running the database, remember to start MySQL and use the specified table in the library.
MySQL--user=user_name--database=you_db\


5. A more practical example

Driver.cxx
//
#include <memory>//Std::auto_ptr
#include <iostream>
#include <odb/database.hxx>//define database class
#include <odb/transaction.hxx>//Definition Transaction class
#include <odb/mysql/database.hxx>//implementation of the database class interface, also include
#include "Person.hxx"
#include "Person-odb.hxx"
using namespace Std;
Using namespace Odb::core;//relative namespace. Use Odb::batabase and odb::transaction directly below, and do not write Odb::core:: Database and Odb::core::transaction.


Int
Main (int argc, char* argv[])
{
Try
{
Auto_ptr<database> db (New odb::mysql::d atabase (argc, argv));//(1)
unsigned long john_id, jane_id, joe_id;
Create a few persistent person objects.
//
{
Person John ("John", "Doe", 33);
Person Jane ("Jane", "Doe", 32);
Person Joe ("Joe", "Dirt", 30);
Transaction T (Db->begin ());//(1)
Make objects persistent and save their IDs for later use.
//
john_id = Db->persist (John);//(2)
jane_id = Db->persist (jane);//(2)
joe_id = Db->persist (Joe);//(2)
T.commit ();//(3)
}
}
catch (const odb::exception& e)
{
Cerr << e.what () << Endl;
return 1;
}
}


Note:
(1) First, we will first create a database object and a transaction object.
In the implementation of ODB, all database operations must be performed within a single transaction. Transaction is an atomic unit of the amount of work we do with the database. A transaction contains a database operation. If a transaction succeeds, the database operation within this transaction will succeed. If a transaction fails at a time, all operations within this transaction will fail.


(2) After we have new many person objects, we use persist to select which objects are stored in the database.


(3) Submit a transaction once. If the program crashes before commit, all the databases that will be saved will not be stored.


Compile the program, then open the database, and then execute the program. To view the records of SQL, we can see the following records:
INSERT into "person" (' id ', ' first ', ' last ', ' age ') VALUES (?,?,?,?)
INSERT into "person" (' id ', ' first ', ' last ', ' age ') VALUES (?,?,?,?)
INSERT into "person" (' id ', ' first ', ' last ', ' age ') VALUES (?,?,?,?)


6. Querying the Database

typedef odb::query<person> Query;
typedef odb::result<person> Result;
Say hello to those over 30.
//
{
Transaction T (Db->begin ());
Result R (db->query<person> (Query::age > 30));
for (Result::iterator I (R.begin ()); I! = R.end (); ++i)
{
cout << "Hello," << I->first () << "!" << Endl;
}
T.commit ();
}
}

7. Updating the database

(1)//Use Object ID
unsigned long john_id, jane_id, joe_id;
Create a few persistent person objects.
//
{
...
Save object IDs for later use.
//
john_id = John.id ();
jane_id = Jane.id ();
joe_id = Joe.id ();
}
Joe Dirt just had a birthday, so update his age.
//
{
Transaction T (Db->begin ());
Auto_ptr<person> Joe (Db->load<person> (joe_id));
Joe->age (Joe->age () + 1);
Db->update (*joe);
T.commit ();
}


(2) Do not use object ID
Joe Dirt just had a birthday, so update his age. An
Alternative implementation without using the object ID.
//
{
Transaction T (Db->begin ());
Result R (db->query<person> (Query::first = = "Joe" &&
Query::last = = "Dirt"));
Result::iterator I (R.begin ());
if (i! = R.end ())
{
Auto_ptr<person> Joe (I.load ());
Joe->age (Joe->age () + 1);
Db->update (*joe);
}
T.commit ();
}

8. Delete Persistent Object

Delete an object to use the ID of the object
John Doe is no. longer in our database.
//
{
Transaction T (Db->begin ());
Db->erase<person> (john_id);
T.commit ();
}


Of course, you can also use the object ID
John Doe is no. longer in our database. An alternative
Implementation without using the object ID.
//
{
Transaction T (Db->begin ());
Result R (db->query<person> (Query::first = = "John" &&
Query::last = = "Doe"));
Result::iterator I (R.begin ());
if (i! = R.end ())
{
Auto_ptr<person> John (I.load ());
Db->erase (*john);
}
T.commit ();
}

Introduction to C + + ORM ODB

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.