The purpose of this article is to understand what the O/R Mapping is, why O/R Mapping, and how to perform the O/R Mapping in the most refined language.
What is the O/R Mapping?
In broad sense, ORM refers to the mutual transformation between object-oriented object model and relational database data structure.
In the narrow sense, ORM can be considered as a data storage based on relational database, which realizes a virtual object-oriented data access interface. Ideally, based on such an object-oriented interface, persisting an Oo object should not require understanding the implementation details of any relational database storage data.
Why do I need O/R Mapping?
Broadly, because we need to object-oriented to describe our business, we also need relational databases to store our data.
One might mention that we don't necessarily use object-oriented to describe the business, or we don't necessarily use relational databases to store data. Yes, but, at least, there are quite a large number of programs that need to be co-operative. Existence is reasonable. Because they need each other at the same time, both are objective and worthy of discussion.
Since it is reasonable to be present in the broad sense, there is no need to discuss why ORM is needed, and many of the discussions on ORM are in fact aimed at the narrow definition mentioned above. But even so far, the really perfect tool for implementing this narrowly defined ORM is not really there (many tools, like Hibernate, are already pretty close, but quite apart from perfection).
Since it does not exist, then, before the discussion needs to be needed, we are afraid to discuss whether it is possible, theoretically, mathematically, object-oriented object model and relational database data structure, in the end can be perfect mapping? To answer this question, we need to solve two difficult problems.
O/R Impedance imbalance
The first conundrum, called the O/R impedance imbalance (O/R impedance mismatch), refers to the conceptual differences between the OO object model and the data structure of the relational database. OO design concept is to describe the real world with the most correct semantics, while the relational database design concept is from the mathematical point of view, how to store and manage data more effectively. Because of the differences in design concepts, they may be similar in data structures, but the focus is often different.
For example:
- From the perspective of OO, every semantic explicit, each object semantic attribute, should be defined as an attribute; from the relational database perspective, it is possible to take into account that some attributes are never used as query criteria, while putting multiple semantic attributes in a certain format, there is a field in a data table, It is also possible that because a set of semantic attributes are used in a completely different frequency from another set of properties, even if they are semantically part of an object, it is possible to split them into two data tables to store them.
- From an OO perspective, objects only care about their intrinsic properties and do not need to be uniquely identified; However, from the perspective of a relational database, each row of data in a single data table needs to be uniquely identified and probably semantically meaningless, such as a self-growing identity.
- From OO angle optimization, generally follow the principle of solid, with more correct semantics to organize objects, from the perspective of relational database optimization, often in order to query performance, to modify the field type, length, modify the index, even the table, sub-Library.
- ...
An ORM tool wants to solve the "O/R Impedance Imbalance" problem perfectly by simply configuring it, which seems to me almost impossible. However, to a certain extent, the vast majority of common mapping strategies supported by flexible configurations, coupled with interfaces that can be extended by users through custom code, should still be pretty close to perfection.
Cultural impedance Imbalance
The second problem, called "cultural impedance imbalance (cultural impedance mismatch)", refers to the cultural differences between relational data specialists and object-oriented experts. The most classic debate about this conundrum is "should the data structure of the relational database be driven, or is the development of the program driven by OO object models?" ”。
The main ideas of OO experts on this controversy are:
My business is the core of the program, the database is only for the needs of my persistent data service, so when designing Oo object model, I should not consider how to store the problem of relational database;
The main points of view of database experts are:
Data is the core wealth of the company, the stability of the data is far stronger than the stability of OO model, the design of database architecture driven by OO model is not guaranteed, and the cost of database maintenance is not acceptable at all.
In fact, the real reason for the argument is "the cultural difference between the relational data expert and the object-oriented expert". Big Bull Scott W Ambler's article Why Data Models shouldn ' t drive Object Models (and Vice Versa) is a good answer to this question.
In the final analysis, since OO and relational database are indispensable parts, need to work together, want to achieve a perfect ORM, not only need good ORM tools, but also need both OO experts and database experts to understand each other's technology and design concepts. For an OO expert, an ORM tool can provide direct support for the common mappings it supports, but OO experts who apply these ORM tools must understand relational databases and know how to design an object model that is more easily mapped to a relational database without affecting the semantics of OO objects. , know how to choose the mapping methods supported by ORM tools, and how to extend the mapping method that ORM cannot easily support with custom code; Similarly, for a relational database expert, you also need to understand OO semantics, and possible refactoring, so that the design of the database structure, more easily mapped to OO objects , it is easier to respond to the refactoring of the Oo object model. This is the true harmony, the true perfection.
Summary
In summary, whether for an OO expert or a relational database expert, you need to understand OO, and understand the relational database, understanding the basic principles of ORM. Without the full knowledge, a perfect ORM tool cannot be used correctly, and with this knowledge, you can take advantage of existing ORM tools to speed up your own work, and rationalize or extend the available ORM tools, or use custom code to implement ORM mappings beyond the capabilities of ORM tools. This is the ideal ORM practice. In the next section, let's talk about the fundamentals of ORM.
How to do O/R Mapping? Simple mapping
1. Class <-> Table
A class can typically be mapped to a table, and a class instance corresponds to a row of data in a table. However, each row of data in a table typically requires a primary key to uniquely identify the row of data, and each instance of a class does not necessarily require a unique identity.
2. Property <-> Field
A class property can be mapped directly to a field in the table. However, their data types do not necessarily match directly. If they represent a data type that is semantically convertible, the type of field should be greater than or equal to the property's data type. If they represent types that are semantically non-convertible, then you need to make a custom transformation at the application level.
Inheritance Mappings
1. Single-table mapping of the entire inheritance system
Using a database table to store data from all classes in the entire inheritance system, the data table needs additional flag fields to differentiate which class of records should be mapped to the inheritance system, which is appropriate for the hierarchy of inheritance systems, the total number of records is relatively small, and the subclass's attribute extension to the parent class is relatively less frequent.
Single-table mapping the advantage of the entire inheritance system is read/write inheritance in the system of each class of data, only need to manipulate a table, performance is good, and, new inheritance classes, or extension class attributes only need to increase or decrease the field of a table can be, easy to maintain; The main disadvantage is that Because all classes in the inheritance system share a table, the table will have more data on the null field values, waste some storage space, and if the number of records is too large, the table will be larger and will affect the read and write performance of the table.
2. A class mapping a specific table
A specific table for a class map is one for each class, and each data table redundancy contains all the attribute fields of its parent class, and the subclass and parent class share the same primary key value. A Class A specific table scheme is suitable for high query performance, the inheritance hierarchy is not too complex, and the base class contains fewer attributes and the subclass extends more attributes, and can withstand certain database redundancy cases.
One of the advantages of a class mapping scheme is that the query performance is good, the read operation only needs to manipulate a table, and the corresponding structure of the entity data is clear, the database table migration and maintenance will be more convenient; The main disadvantage is that data redundancy is large, because each time a subclass of data is inserted, Also insert a copy of the data from the parent class containing the child class into all the parent class hierarchy tables.
3. A class mapping an extension table
The so-called one class map, an extension table, refers to a data table for each class in the inheritance system, but each subclass does not redundantly contain all the properties of the parent class, but only the extended properties and shared primary key values. A class map an extension table scheme is suitable for a very complex inheritance system, structurally variable, and wants to minimize the data redundancy situation.
The advantage of a class mapping for an extended table scheme is that it is structurally flexible, that it is convenient to add subclasses or insert intermediate inheritance classes, and that there is minimal redundancy, but the disadvantage is that both read and write operations involve subclasses and all parent classes. When reading an operation, you must naturally link to the data table of all the parent classes, and when inserting or updating the data, you also need to write all the parent class tables.
4. The common table structure maps all the class
This approach not only supports the use of a single table to store an inheritance system, it can even support, with a table to store any number of different classes. Its principle is metadata-driven. Each row of this table contains a type of identification field, a field representing the class's property name, and a field representing the class's property value. At run time, the value of all the property that describes a class instance is taken out by a unique identity, and then mapped according to the property's name.
For an example analysis of various inheritance mappings and a detailed comparison of pros and cons, see: O/R Mapping in Detail of Scott W. Ambler.
Association mappings
1. One-to-one correlation, one-to-many associations (including one-to-one and one-to-many autocorrelation)
The so-called one-to-one association, in fact, can be divided into three cases, namely 0. 1-1,1–1,1–0..1 three cases, while a one-to-many association is divided into *-1 and 1-*.
The 1th of the following three scenarios is the most commonly used mapping scheme, followed by scenarios that can be referred to in some special cases:
1) The most common scenario is to add a foreign key to the corresponding table of the referenced object for the table that requires other object references, except that the entity class code corresponding to the table needs to be defined as a set type for the "many" end of a one-to-many scenario;
2) in Hibernate is called "component (Component) mapping", for example, if the person class contains a property of an address member type, and address consists of City,street,zipcode three member properties, If the address is not used by other objects in addition to the person association, then we can consider using only one data table person to persist the two tables of person and address, The Person data table contains a collection of all the attributes in the person class except address and the address class, and of course, the mapping relationship needs to be specifically specified in the metadata;
3) There is also a persistence scheme for the person,address two classes in the above scenario in which all properties of the address type are serialized first, then stored in the field address of the person table, so that two classes can be persisted with just one table, of course, In this scenario, the data volume of the serialized object members should be as small as possible;
4) Another option is to share a one-to-one association with the same primary key value. It would have been possible to put it in another table with a field that was relatively less frequently used in one table, so that the records of the two tables could be associated with the same primary key.
2. Many-to-many associations (including many-to-many self-associations)
The so-called many-to-many association nature is *-* this situation. It is generally necessary to have an association table that contains the primary key of the associated parties, and to link the associated table and data table when fetching the data.
English information
- Http://en.wikipedia.org/wiki/Object-relational_mapping
- Http://www.agiledata.org/essays/impedanceMismatch.html
- Http://www.agiledata.org/essays/culturalImpedanceMismatch.html
- Http://www.agiledata.org/essays/drivingForces.html
- Http://www.agiledata.org/essays/mappingObjects.html