Object-Relational Mapping (ORM)| Full Explanation (Definition, usage, structure and practice)
Tags: programming, beginners, tutorial, detectalalogica
Published: 2023-07-14 19:29:31

Object-Relational Mapping (ORM)| Full Explanation (Definition, usage, structure and practice)

# Introduction

Hello, my name is Daniela Barazarte and I want to welcome you to this complete explanation about ORM (Object-Relational Mapping). This explanation will be intuitive and simple as well as all the explanations that are part of #DetectaLaLogica.

If you prefer videos, here is a complete tutorial made by me on YouTube, it's in Spanish but it also has subtitles: https://www.youtube.com/watch?v=XIkDO9aPX_4

# <u>Theory</u>
## Definition of each word
**Object Relational Mapping (ORM)*
- Object (Object): in OOP, it is an instance of a class that has attributes and methods that allow it to perform certain actions and manipulate data.
- Relational (Relational): relational database is a data structure organized into tables that are interconnected by relationships.
- Mapping: is a way of translating between the objects of a programming language and the tables of a relational database.

## Full definition
It is a software engineering technique used to connect a relational database and an object-oriented programming language.

![ORM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6187jygz44jm5m5qc5lm.png)

## #DetectTheLogic
ORM is called Object-Relational Mapping (Object-Relational Mapping) because it is a technique of mapping objects of an object-oriented programming language with tables of a relational database.

# <u>Use</u>
## So that
Instead of having to write SQL queries directly, developers can interact with objects in the programming language that represent the data in the database.

## When and where
It is used in a wide variety of software applications, from web applications to desktop and mobile applications. It is especially useful in applications that handle large amounts of data and require efficient access to the database.

## As
- Hibernate: ORM for Java.
- Entity Framework: ORM for .NET/C#
- Django ORM: Default ORM for Django.
- Sequel: ORM for Ruby.
- SQLAlchemy: ORM for Python.
- Eloquent: ORM for PHP that is used in the Laravel framework.


# <u>Practice</u>
## Exercise
You have a web application for an online store that sells electronics. You must store and manage the information of products, customers, orders and financial transactions using an OOP language.

### **Method: SQL**
I need to create the database, then create the customer table and be able to insert data there... but it's not that useful considering that I can't do it directly from the web page

```
-- Create a customer:
INSERT INTO clients (Name, Email)
VALUES('client name', 'client email');

-- Read all customers:
SELECT * FROM clients;

-- Edit a client
UPDATE clients
SET Name = 'new client name', Email = 'new client email'
WHERE Id = client id;

-- Delete a client
DELETE FROM clients
WHERE Id = client id;
```

### **Method: ORM**
With Csharp(Programming Language) AND Entity Framework(ORM) I can make the data come directly to the database from the web page. The database that I will use will be MySql and I will need different things but I can highlight the DbContext that is usually used in this ORM
```
public class MyDbContext : DbContext
     {
         // Add the connection line to the database in MySQL
         internal readonly string connectionString = "server=localhost;port=3306;database=dbclients";
        
         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
         {
             // Declare the use of MySQL and send the connection line and the MySQL version
             optionsBuilder.UseMySql(connectionString, new MySqlServerVersion(ServerVersion.AutoDetect(connectionString)));
         }
         // Declare the table to be used
         public DbSet<Client> Clients { get; set; }
     }
```
Once the connection is made, I'm going to need to do migrations and from there I can start doing certain functions directly from the project.

An example is the add client function:
```
// Function to add a new customer to the database
static void AddClient(MyDbContext db)
{
     // Print a message to indicate that a new customer is being added
     Console.WriteLine("\nAdding a new client...");

     // Prompt the user to enter the customer's name and email
     Console.Write("Name: ");
     string name = Console.ReadLine();
     Console.Write("Email: ");
     string email = Console.ReadLine();

     // Create a new Client object with the data entered by the user
     var newClient = new Client
     {
         Name = name,
         email = email
     };

     // Add the new customer object to the database
     db.Clients.Add(newClient);

     // Save the changes to the database
     db.SaveChanges();

     // Print a message to indicate that the new customer has been added to the database
     Console.WriteLine($"Added client: {newClient.Name} ({newClient.Email})");
}
```
And similar functions can be performed for reading, editing and deleting.

And just like that, you can interact with a database directly from your application without even using SQL language.

# Importance
**ORM has several benefits:**

- Database abstraction
- Reduced development time
- Code portability
- Ease of maintenance
- Security for injection attacks
- Work more efficient and faster

# Farewell
(Remember) #DetectaLaLógica: ORM is called Object-Relational Mapping (Object-Relational Mapping) because it is a technique of mapping objects from an object-oriented programming language with relational database tables.

You can practice this topic in my GitHub repository (C# language code): https://github.com/danielabarazarte/DetectaLaLogica

Thank you very much for reading, if my post helped you, you can give it a LIKE so that more people can read it, you can also comment on any questions or suggestions you have and I appreciate you following me to see more posts of this style, thanks <3.