
Object-relational mapping (O/RM) is a programming technique for converting data between a relational database and the memory of an object-oriented programming language. This creates a virtual object database that can be used from within the program. In object-oriented programming, data-management tasks act on objects that combine scalar values into objects. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a "Person object" with an attribute/field to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain "PhoneNumber objects" and so on.
SELECT * FROM users
WHERE age > 21
AND city = 'New York'; User.query.filter(
User.age > 21,
User.city == 'New York'
).all() How ORM Works
ORM acts as a translator between object-oriented programming languages and relational databases. It allows developers to interact with a database using their preferred programming language instead of writing queries directly. This makes database operations more developer-friendly by writing database queries using familiar programming concepts, reducing boilerplate code and repetitive SQL statements, providing built-in security features against SQL injection, and making it easier to switch between different databases.
Popular ORMs
- SQLAlchemy: A popular ORM for Python, used in web frameworks like Django.
- Hibernate: A widely used ORM for Java.
- Sequelize: An ORM for JavaScript, commonly used in Node.js applications.
Example: ORM vs. Raw SQL
Without ORM (Raw SQL): “` SELECT * FROM users WHERE age > 21 AND city = 'New York'; “` With ORM (Python using SQLAlchemy): “` User.query.filter( User.age > 21, User.city == 'New York' ).all() “` ORM simplifies database operations and makes code more maintainable by allowing developers to work with database records as if they were objects in their preferred programming language.
Additional Acronyms for ORM
- ORM - Online Reputation Management