Junior — Middle
Could you explain the principle and the operation of registry objects in conjunction with databases, known as ORM?
sobes.tech AI
Answer from AI
Object-Relational Mapping (ORM) is a technology that allows working with a database through objects in code, hiding SQL details and data transformation.
How it works:
- Each database table maps to a class (object) in the programming language.
- Rows correspond to instances of these classes.
- Table columns are object attributes.
Objects-registries (entity objects) represent database records and contain methods for reading, modifying, and saving data.
Advantages:
- Simplifies data handling — developers work with objects, not SQL.
- Automatic management of relationships between tables.
- Caching and query optimization.
Example in Python with SQLAlchemy:
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# Create a new user
new_user = User(name='Alice')
session.add(new_user)
session.commit()
# Query user
user = session.query(User).filter_by(name='Alice').first()
print(user.name) # Alice
Thus, ORM allows working with database as objects, increasing convenience and reducing errors.