ORM: управление объектно-реляционным отображением данных
ORM (Object-Relational Mapping)
ORM (Object-Relational Mapping) is a technology that allows object-oriented code to interact with a relational database, represented as relational tables. It simplifies working with data and eliminates the need to manually write SQL queries, enabling programmers to use objects and methods to interact with the database.
ORM solves the problem of the difference between object-oriented and relational data representation by automatically mapping objects to corresponding tables and records in the database. This allows programmers to work with data as ordinary objects, calling methods to create, update, read, and delete data, while the ORM generates and executes the corresponding SQL queries. This approach greatly simplifies and speeds up application development.
An example of a popular ORM library is SQLAlchemy for the Python programming language. Below are code examples demonstrating the use of SQLAlchemy to work with a database.
First, you need to create a model (class) for a table in the database. For example, we can have a table "Users" with fields "id", "name", "age". The code to create the model may look as follows:
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'Users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
Next, we can use ORM methods to perform data operations, such as creating a new user:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('mysql://username:password@localhost/database_name')
Session = sessionmaker(bind=engine)
session = Session()
new_user = User(name='John', age=25)
session.add(new_user)
session.commit()
This code will create a new user with the specified name and age values in the "Users" table and save the changes to the database.
ORM also allows for querying data based on various criteria, updating existing records, or deleting them. Code examples for these operations are provided below:
# Querying users older than 30 years
users = session.query(User).filter(User.age > 30).all()
# Updating the age of a user named "John"
user = session.query(User).filter_by(name='John').first()
user.age = 27
session.commit()
# Deleting a user named "Peter"
user = session.query(User).filter_by(name='Peter').first()
session.delete(user)
session.commit()
Thus, ORM greatly simplifies working with a database, allowing programmers to focus on the application logic rather than writing complex SQL queries. It improves performance, enhances maintainability, and makes code more readable and understandable.