![]() |
VOOZH | about |
In modern web development, efficiently managing databases is important for building scalable and high-performing applications. Two popular methods for interacting with databases are ORM (Object-Relational Mapping) and ODM (Object-Document Mapping). Though both are used to bridge the gap between programming code and databases, they serve different purposes.
ORM is a method used for relational databases with structured data and clear schemas. It works well for apps with complex relationships. ORM translates code objects into database tables and back, allowing developers to work with familiar objects and classes instead of writing complex SQL queries.
create_engine() function connects to a PostgreSQL database, and Base.metadata.create_all(engine) creates the users table if it doesn't exist.session.add() and saved to the database with session.commit().session.query(User).all() retrieves all users from the table, and their names and emails are printed.Query:
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
# Define a User class mapped to the 'users' table
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
# Connect to the database
engine = create_engine('postgresql://user:password@localhost/dbname')
Base.metadata.create_all(engine)
# Create a session
Session = sessionmaker(bind=engine)
session = Session()
# Add a new user to the 'users' table
new_user = User(name="Abc", email="abc@example.com")
session.add(new_user)
session.commit()
# Query users from the 'users' table
users = session.query(User).all()
for user in users:
print(user.name, user.email)
Output:
Abc abc@example.comExplanation:
User class defines a table called users with three columns: id, name, and email. ODM is used for designing NoSQL databases. It provides flexibility for modeling data and works well with semi-structured or changing data that needs to scale. This approach is great for apps with flexible data structures that may change over time.
User model and saved to the MongoDB collection via newUser.save().User.find() function retrieves all user documents from the MongoDB collection, and their name and email are printed.Query:
const mongoose = require('mongoose');
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase');
// Define a User schema and model
const userSchema = new mongoose.Schema({
name: String,
email: String,
});
const User = mongoose.model('User', userSchema);
// Create a new user document
const newUser = new User({ name: 'Abc', email: 'abc@example.com' });
newUser.save().then(() => console.log('User saved'));
// Query all user documents
User.find().then(users => {
users.forEach(user => console.log(user.name, user.email));
});
Output:
Abc abc@example.comExplanation:
User schema is defined with two fields, name and email, in MongoDB. Aspects | ORM | ODM |
|---|---|---|
Primary Use | It Maps code objects to tables in relational databases. | It Maps code objects to documents in NoSQL databases. |
Database Type | It is Used with relational databases (e.g., MySQL, PostgreSQL). | It is Used with document-based NoSQL databases (e.g., MongoDB, CouchDB ). |
Data Structure | It is Structured with tables , rows and columns. | It is Flexible and document-based (usually as JSON or BSON format ). |
Schema-Requirement | It requires predefine and rigid schema | It requires flexible schema, allowing varying document structures within the collection. |
Query Language | Uses SQL (Structured Query Language). | Uses NoSQL-specific query languages (e.g., MongoDB's syntax) |
Example Tools | SQLAlchemy (Python),hibernate(Java), Sequelize(Node.js). | Mongoose (JavaScript Node.js), Doctrine ODM(PHP) Morphia (Java). |
Suitability | Best for applications with complex relationship and rigid schema. | Best for applications with dynamic, evolving data models and needs horizontal scaling. |
Data Relationships | Handles relationships like one-to-one, one-to-many, many-to-one, many-to-many. | Handles nested documents and arrays, making it easier to model hierarchical data. |