Object Relational Mapping (ORM)

🎯 Objectives: Object Relational Mapping (ORM)

ORM (Object-Relational Mapping) Notes

Object Relational Mapping (ORM) - Full Notes

1. What is ORM?

ORM (Object-Relational Mapping) is a programming technique used to interact with relational databases using object-oriented programming (OOP) concepts. Instead of writing raw SQL queries, developers use objects, classes, and methods to work with the database.

2. Why Use ORM?

  • Reduces the need to write raw SQL manually.
  • Allows reusability of objects and classes.
  • Improves security by helping prevent SQL injection.
  • Improves productivity due to faster development.
  • Makes the codebase easier to understand and maintain.

3. How ORM Works (Simplified)

  • Each class is mapped to a database table.
  • Each object is mapped to a row in the table.
  • Each class attribute is mapped to a column in the table.

4. Common ORM Operations

Operation ORM Equivalent (Example in Python SQLAlchemy)
Create new_user = User(name="John")
session.add(new_user)
Read (All) users = session.query(User).all()
Read (One) user = session.query(User).filter_by(id=1).first()
Update user.name = "Mike"
session.commit()
Delete session.delete(user)
session.commit()

5. ORM Components

  • Entity: The object or class representing a table.
  • Session or Entity Manager: Manages connections and executes queries.
  • Mapping: The configuration that connects classes to tables.
  • Schema: The structure of the database as seen by the ORM.

6. Popular ORM Libraries

Programming Language ORM Tool
Python SQLAlchemy, Django ORM
PHP Eloquent (Laravel), Doctrine
Java Hibernate
JavaScript Sequelize, TypeORM
C# Entity Framework

7. Example in PHP (Laravel Eloquent)

class User extends Model {
    protected $table = 'users';
}

// Create
$user = new User();
$user->name = "John";
$user->save();

// Read
$users = User::all();

// Update
$user = User::find(1);
$user->name = "Mike";
$user->save();

// Delete
$user->delete();
  

8. Advantages of ORM

  • Speeds up development time.
  • Reduces the amount of raw SQL.
  • Makes code more readable and maintainable.
  • Improves developer productivity.
  • Integrates well with MVC frameworks.

9. Disadvantages of ORM

  • May cause performance overhead compared to raw SQL.
  • Reduces direct control over SQL queries.
  • Can be difficult to debug complex queries.
  • Has a learning curve for beginners.

10. When to Use or Avoid ORM

Use ORM when: Avoid ORM when:
Working on small to medium-scale applications Maximum performance is critical
Need faster and cleaner development Handling complex or custom SQL queries
Using modern web frameworks Integrating with legacy systems or databases

11. Real-Life Analogy

  • A class is like a database table.
  • An object is like a row in the table.
  • An attribute is like a column in the table.

12. Extra Concepts

Lazy vs Eager Loading

  • Lazy Loading: Data is loaded only when needed.
  • Eager Loading: Related data is loaded immediately.

Migration

Migrations are used to define and change database schemas using code, usually in ORM-based frameworks.

Relationships

  • One-to-One
  • One-to-Many
  • Many-to-Many
public function posts() {
    return $this->hasMany(Post::class);
}
  

13. Summary

Concept Description
ORM Technique for connecting object-oriented code with relational databases
Advantages Faster development, maintainable code, less SQL
Common Tools Eloquent, Django ORM, SQLAlchemy, Hibernate
Limitations Performance, control, complexity in large systems

FULL SUMMARY

Object Relational Mapping (ORM) is a technique used in creating a "bridge" between object-oriented programs and, in most cases, relational databases. Put another way, you can see the ORM as the layer that connects object oriented programming (OOP) to relational databases. When interacting with a database using OOP languages, you'll have to perform different operations like creating, reading, updating, and deleting (CRUD) data from a database. By design, you use SQL for performing these operations in relational databases. While using SQL for this purpose isn't necessarily a bad idea, the ORM and ORM tools help simplify the interaction between relational databases and different OOP languages. What is an ORM Tool? An ORM tool is software designed to help OOP developers interact with relational databases. So instead of creating your own ORM software from scratch, you can make use of these tools. Here's an example of SQL code that retrieves information about a particular user from a database: "SELECT id, name, email, country, phone_number FROM users WHERE id = 20" The code above returns information about a user β€” name, email, country, and phone_number β€” from a table called users. Using the WHERE clause, we specified that the information should be from a user with an id of 20. On the other hand, an ORM tool can do the same query as above with simpler methods. That is: users.GetById(20) So the code above does the same as the SQL query. Note that every ORM tool is built differently so the methods are never the same, but the general purpose is similar. ORM tools can generate methods like the one in the last example. Most OOP languages have a variety of ORM tools that you can choose from. Here are some of the most popular for Java, Python, PHP, and .NET development: Popular ORM Tools for Java 1. Hibernate Hibernate enables developers to write data persistent classes following OOP concepts like inheritance, polymorphism, association, composition. Hibernate is highly performant and is also scalable. 2. Apache OpenJPA Apache OpenJPA is also a Java persistence tool. It can be used as a stand-alone POJO (plain old Java object) persistence layer. 3. EclipseLink EclipseLink is an open source Java persistence solution for relational, XML, and database web services. 4. jOOQ jOOQ generates Java code from data stored in a database. You can also use this tool to build type safe SQL queries. 5. Oracle TopLink You can use Oracle TopLink to build high-performance applications that store persistent data. The data can be transformed into either relational data or XML elements. Popular ORM Tools for Python 1. Django Django is a great tool for building web applications rapidly. 2. web2py web2py is an open source full-stack Python framework for building fast, scalable, secure, and data-driven web applications. 3. SQLObject SQLObject is an object relational manager that provides an object interface to your database. 4. SQLAlchemy SQLAlchemy provides persistence patterns designed for efficient and high-performing database access. Popular ORM Tools for PHP 1. Laravel Laravel comes with an object relational manager called Eloquent which makes interaction with databases easier. 2. CakePHP CakePHP provides two object types: repositories which give you access to a collection of data and entities which represents individual records of data. 3. Qcodo Qcodo provides different commands that can be run in the terminal to interact with databases. 4. RedBeanPHP RedBeanPHP is a zero config object relational mapper. Popular ORM Tools for .NET 1. Entity Framework Entity Framework is a multi-database object-database mapper. It supports SQL, SQLite, MySQL, PostgreSQL, and Azure Cosmos DB. 2. NHibernate NHibernate is an open source object relational mapper with tons of plugins and tools to make development easier and faster. 3. Dapper Dapper is a micro-ORM. It is mainly used to map queries to objects. This tool doesn't do most of the things an ORM tool would do like SQL generation, caching results, lazy loading, and so on. 4. Base One Foundation Component Library (BFC) BFC is a framework for creating networked database applications with Visual Studio and DBMS software from Microsoft, Oracle, IBM, Sybase, and MySQL You can see more ORM tools here. Now let's discuss some of the advantages and disadvantages of using ORM tools. Advantages of Using ORM Tools Here are some of the advantages of using an ORM tool: It speeds up development time for teams. Decreases the cost of development. Handles the logic required to interact with databases. Improves security. ORM tools are built to eliminate the possibility of SQL injection attacks. You write less code when using ORM tools than with SQL. Disadvantages of Using ORM Tools Learning how to use ORM tools can be time consuming. They are likely not going to perform better when very complex queries are involved. ORMs are generally slower than using SQL. Summary In this article, we talked about Object Relational Mapping. This is a technique used to connect object oriented programs to relational databases.

πŸ“– Reference Book: N/A

πŸ“„ Page: 1