Acquainted with Object [Relational | Document | Graph] Mapper

Preliminary


May already be familiar to you in terms of data definition languagedalam relational database operations. You can create a table that has a column - specific columns that will store the data from your application. Besides the relational database has the ability to connect with other tables, so you can make atomic information and can freely redundant once you design database design capable of handling it. In building a relational sebuahdatabase, some use raw SQL that is executed through the console used a relational database. Some are using software modeler that has the ability to draw the first entity relationship diagram (ERD), then do forward engineering that will automatically generate the main table and relational table based ERD designed.
Merancang database relasional menggunakan CASE (Computer Aided Software Engineering)
Designing a relational database using a CASE (Computer Aided Software Engineering)
But some developers who utilize technologist known as object relational mapper (ORM), a technology where we can create a database simply by defining a class in a particular programming language, and then perform the establishment of a database of the class definition. Now, the object mapper to the database is not only available for relational databases only. Database-based documents such as MongoDB and Neo4j graph object mapper also has called the document object mapper (ODM) and the graph object mapper OGM. Of course, the technology exists to assist developers in building a database by reducing the manual activity that is often performed as did the manufacture of tables or collections.
As an example for this article, Python will be used to show examples of the use of ORM, ODM, and OGM. Curious? let's continue the discussion below:


1. Object Relational Mapper (ORM)

 Generally Object ORM is a tool that will make up the tables in a database based on the class defined by the developer. ORM has a method that can be used to interact with tabeltanpa have to do SQL directly. Fieldrelasional can form without doing alter the destination table. If you perform a database engine displacement can easily be done without the need to remodel a lot of data definition language in the usual way.
ORM that will be used is SQLAlchemy. SQLAlchemy can help you by using a method on the SQLAlchemy or using raw SQL when the process will be conducted fairly complex. For example we will create a database that stores various types of database engines. We will use SQLite for storage:


engine = create_engine('sqlite:///codepolitan.db')
Base = declarative_base()
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()

Then we create a class that represents the table Category and DB_Engine like the cut of the following classes:

class Category(Base):
    __tablename__ = 'category'

    id = Column (Integer, Sequence('category_id_seq'), primary_key=True)
    name = Column (String, nullable=False)

    def __repr__(self):
        return "Category - %s" % (self.name)

class DB_Engine(Base):
    __tablename__ = 'db_engine'

    id = Column (Integer, Sequence('db_engine_id_seq'), primary_key=True)
    name = Column (String, nullable=False)
    category_id = Column(Integer, ForeignKey('category.id'))
    category = relationship("Category", backref=backref('db_engine', order_by=id))

    def __repr__(self):
        return "DB_Engine - %s" % (self.name)
In the source code above we define the columns with a local variable in a class, the field will be a column in a table on the database engine you use. Then to the relationship table, you simply designate one field in another class. In the process of filling any tables, SQL is not used directly but melaluimethod owned an ORM:

category_1 = Category(name='document-based database')
session.add(category_1)
category_2 = Category(name='relational database')
session.add(category_2)
session.commit()

session.add_all([
    DB_Engine(name="MySQL", category=category_2),
    DB_Engine(name="MariaDB", category=category_2),
    DB_Engine(name="PostgreSQL", category=category_2),
    DB_Engine(name="SQLite", category=category_2),
    DB_Engine(name="MongoDB", category=category_1),
    DB_Engine(name="CouchDB", category=category_1),
])
session.commit()
And lastly, you can perform queries by calling just chaining method without having to create SQL fairly long for the same thing

list_db = session.query(DB_Engine).join(Category).all()
for db in list_db:
    print db.name , " is ", db.category.name
Some examples of other FORM already available include:
  • PHP: Propel, Doctrine, Readbean, Phalcon ORM, Symfoyny ORM
  • Python: SQLAlchemy, Django ORM
  • Java: Cayenne, Hibernate, ORMLite
  • Ruby: Rails Active Record, DataMapper
  • Node.js: Sequelize, Bookshelf, Node ORM, Waterline
  • Go: Gorm
  • Erlang: Hiberl
  • Perl: PerlORM, DBIx::Class
  • C#: NHibernate
  • C++: ODB, YB-ORM

ORM berhasil dijalankan, data tersimpan ke SQLite3 dan isi tabel pun dapat diambil untuk ditampilkan
ROM is successfully executed, the data is stored to SQLite3 and table of contents can be retrieved for display
Isi tabel Category dan DB_Engine yang dihasilkan secara otomatis oleh ORM
Category table content and DBEngine generated automatically by the ORM

2. Object Document Mapper (ODM)


Similar to ROM's just that every class is defined to represent sebuahdocument are automatically saved into a collection. You do not need to call first calling name and then save the document collection into it, with ODM you simply create an instance of a class that is derived from the Document, then the object can perform data storage to collectiontertentu. This time we will use the ODM called MongoEngine.
First we have to connect to the MongoDB server that we will use:

connect('codepolitan') 
Then we have to define the class which is the inheritance of the Document property of MongoEngine. We can skip validation that fieldname unallocated empty. Moreover we can create a field that references a collections with ease:

class Category(Document):
    name = StringField(required=True)

class DB_Engine(Document):
    name = StringField(required=True)
    category = ReferenceField(Category)
Now we make some of the documents for collection Category and DBEngine. Only by Category pass objects when the objects instantiated DB_Engine, you can store a value that does DB_Engine reference table to Category:

cat_1 = Category(name='document-based database')
cat_2 = Category(name='relational database')
cat_1.save()
cat_2.save()

db_1 = DB_Engine(name="MySQL", category=cat_2)
db_2 = DB_Engine(name="SQLite", category=cat_2)
db_3 = DB_Engine(name="PostgreSQL", category=cat_2)
db_4 = DB_Engine(name="MariaDB", category=cat_2)
db_5 = DB_Engine(name="MongoDB", category=cat_1)
db_6 = DB_Engine(name="CouchDB", category=cat_1)
db_1.save()
db_2.save()
db_3.save()
db_4.save()
db_5.save()
db_6.save()
Then to query, you simply call the object of a class without passing through instantiation. Columns that refer to Category was already taken automatically without having to take it again manually:

for item in DB_Engine.objects:
    print item.name, ' is ', item.category.name
Some examples of other ODM are already available include:
  • PHP: Mandango, Doctrine MongoDB-ODM, Phalcon ODM
  • Python: MongoEngine, RethinkDB ODM, MongoAlchemy, Ming
  • Java: Mongolink
  • Ruby: Mongoid
  • Node.js: Mongoose
  • Go: Sleep
  • Erlang: Mongrel
  • Perl: Moose, Mandel
  • C#: MongoMapper.NET
  • C++: ODB
ODM berhasil dijalankan, data tersimpan ke MongoDB dan isi collection pun dapat diambil untuk ditampilkan
ODM successfully executed, the stored data to MongoDB and the collection can be retrieved for display
Isi collection Category dan DB_Engine yang dihasilkan secara otomatis oleh ODM
Contents collection Category and DBEngine generated automatically by ODM

3. Object Graph Mapper (OGM)


OGM is almost similar to ORM. Only OGM is provided for the graph database. If the class is defined in ORM is used to create the table, then the graph database defining the class is done for membuatnode. While relations in class will form an arrow that has a direction from a node to the destination node. In the graph there is a two-way relationship, where it will do the queries in the process of traversal. In this example, OGM to be used is Neomodel. For example the case, we use the example case discussion ORM. We start by creating a class that defines the node:


class Category(StructuredNode):
    name = StringProperty(unique_index=True, required=True)

class Dbengine(StructuredNode):
    name = StringProperty(unique_index=True, required=True)
    category = RelationshipTo(Category, 'IS')
Then we create a node for Category and DB_Engine:
  
cat_1 = Category(name='relational database').save()
cat_2 = Category(name='document-based database').save()

db_1 = Dbengine(name='MySQL').save()
db_2 = Dbengine(name='PostgreSQL').save()
db_3 = Dbengine(name='SQLite').save()
db_4 = Dbengine(name='MariaDB').save()
db_5 = Dbengine(name='MongoDB').save()
db_6 = Dbengine(name='CouchDB').save()
The difference with the document-based and relational database, you must connect each node if you want to form a relationship or linkage of data:

db_1.category.connect(cat_1)
db_2.category.connect(cat_1)
db_3.category.connect(cat_1)
db_4.category.connect(cat_1)
db_5.category.connect(cat_2)
db_6.category.connect(cat_2)
You also do not need a cypher query language to retrieve a node. It's just to get the results of a query with multiple lines, you still need a cypher query language to the desired result:

cat_1 = Category.index.get(name='relational database')
results = cat_1.cypher('MATCH (db: Dbengine)-[r:IS]->n return db.name, n.name')

for item in results[0]:
    print item[0], ' is ', item[1]
OGM successfully execute, the data is stored into the Neo4j graph and content can be retrieved for display
  • Python: Neomodel, Mogwai
  • Ruby: neo4j
  • PHP: Neo4j PHP OGM
  • Java: Spring Data Neo4j, Object Graph Mapper
  • Node.js: Gremlin, Mogwai
  • Go: Titan
  • Perl: REST:Neo4p

OGM berhasil dijalankan, data tersimpan ke Neo4j dan isi graf pun dapat diambil untuk ditampilkan
OGM successfully executed, the data is stored into Neo4j graph and content can be retrieved for display
Isi graf Category dan DB_Engine yang dihasilkan secara otomatis oleh OGM
Fill graf Category and DBEngine generated automatically by OGM

Closing


In general objectmapper for database built upon the basic drivers, eg Neomodel built upon Py2Neo and others. Only denganobject this mapper, you can maintain consistency when such data into the table, node, or document. Some features of the object mapper who does that include validation on every column, as in the example above ORM, we pass the value required = Truepada column names because the field can not be empty.
Then one of the benefits of ORM is easily integrated with a web framework, it is possible to do is when you switch web framework program code that you use will not change much during the configuration object mapper you are still appropriate.
By using object mapper to the database, you can easily build a database and can reduce the interaction dengandatabase already in general use. Even using ORM / ODM / OGM, you can reduce some difficulties when using native database drivers. The use of the tools above relies heavily on planning your team, because it could be among your team mates, there were more favored conventional way to manage a database of the applications that you develop.
For the complete source code above, you can download here. May be useful.

(rfs/wikipedia/nosql-database)

0 Response to "Acquainted with Object [Relational | Document | Graph] Mapper"

Posting Komentar