Object–relational mapping

Object–relational mapping (ORM, O/RM, and O/R mapping tool) in computer science is a programming technique for converting data between a relational database and the memory (usually the heap) of an object-oriented programming language. This creates, in effect, a virtual object database that can be used from within the programming language.

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. Each such address-book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as methods to return the preferred phone number, the home address, and so on.

By contrast, relational databases, such as SQL, group scalars into tuples, which are then enumerated in tables. Tuples and objects have some general similarity, in that they are both ways to collect values into named fields such that the whole collection can be manipulated as a single compound entity. They have many differences, though, in particular: lifecycle management (row insertion and deletion, versus garbage collection or reference counting), references to other entities (object references, versus foreign key references), and inheritance (non-existent in relational databases). As well, objects are managed on-heap and are under full control of a single process, while database tuples are shared and must incorporate locking, merging, and retry. Object–relational mapping provides automated support for mapping tuples to objects and back, while accounting for all of these differences.[1]

The heart of the problem involves translating the logical representation of the objects into an atomized form that is capable of being stored in the database while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent.[1]

Overview

Implementation-specific details of storage drivers are generally wrapped in an API in the programming language in use, exposing methods to interact with the storage medium in a way which is simpler and more in line with the paradigms of surrounding code.

The following is a simple example, written in C# code, to execute a query written in SQL using a database engine.

var sql = "SELECT id, first_name, last_name, phone, birth_date, sex, age FROM persons WHERE id = 10";
var result = context.Persons.FromSqlRaw(sql).ToList();
var name = result[0]["first_name"];

In contrast, the following makes use of an ORM-job API which makes it possible to write code that naturally makes use of the features of the language.

var person = repository.GetPerson(10);
var firstName = person.GetFirstName();

The case above makes use of an object representing the storage repository and methods of that object. Other frameworks might provide code as static methods, as in the example below, and yet other methods may not implement an object-oriented system at all. Often the choice of paradigm is made for the best fit of the ORM into the surrounding language's design principles.

var person = Person.Get(10);

Comparison with traditional data access techniques

Compared to traditional techniques of exchange between an object-oriented language and a relational database, ORM often reduces the amount of code that needs to be written.[2]

Disadvantages of ORM tools generally stem from the high level of abstraction obscuring what is actually happening in the implementation code. Also, heavy reliance on ORM software has been cited as a major factor in producing poorly designed databases.[3]

Object-oriented databases

Another approach is to use an object-oriented database management system (OODBMS) or document-oriented databases such as native XML databases that provide more flexibility in data modeling. OODBMSs are databases designed specifically for working with object-oriented values. Using an OODBMS eliminates the need for converting data to and from its SQL form, as the data is stored in its original object representation and relationships are directly represented, rather than requiring join tables/operations. The equivalent of ORMs for document-oriented databases are called object-document mappers (ODMs).

Document-oriented databases also prevent the user from having to "shred" objects into table rows. Many of these systems also support the XQuery query language to retrieve datasets.

Object-oriented databases tend to be used in complex, niche applications. One of the arguments against using an OODBMS is that it may not be able to execute ad-hoc, application-independent queries.[citation needed] For this reason, many programmers find themselves more at home with an object-SQL mapping system, even though most object-oriented databases are able to process SQL queries to a limited extent. Other OODBMS provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving well-known query patterns.[citation needed]

Challenges

A variety of difficulties arise when considering how to match an object system to a relational database. These difficulties are referred to as the object–relational impedance mismatch.[4]

An alternative to implementing ORM is use of the native procedural languages provided with every major database. These can be called from the client using SQL statements. The Data Access Object (DAO) design pattern is used to abstract these statements and offer a lightweight object-oriented interface to the rest of the application.[5]

ORMs are limited to their predefined functionality, which may not cover all edge cases or database features. They usually mitigate this limitation by providing users with an interface to write raw queries, such as Django ORM.[6]

See also

References

  1. ^ a b "What is Object/Relational Mapping?". Hibernate Overview. JBOSS Hibernate. Retrieved 27 January 2022.
  2. ^ Douglas Barry, Torsten Stanienda, "Solving the Java Object Storage Problem," Computer, vol. 31, no. 11, pp. 33-40, Nov. 1998, Excerpt at https://www.service-architecture.com/articles/object-relational-mapping/transparent-persistence-vs-jdbc-call-level-interface.html Lines of code using O/R are only a fraction of those needed for a call-level interface (1:4). For this exercise, 496 lines of code were needed using the ODMG Java Binding compared to 1,923 lines of code using JDBC.
  3. ^ Josh Berkus, "Wrecking Your Database", Computer, Aug. 2009, https://www.toolbox.com/tech/data-management/blogs/wrecking-your-database-080509/
  4. ^ Object–Relational Mapping Revisited - A Quantitative Study on the Impact of Database Technology on O/R Mapping Strategies. M Lorenz, JP Rudolph, G Hesse, M Uflacker, H Plattner. Hawaii International Conference on System Sciences (HICSS), 4877-4886 (DOI:10.24251/hicss.2017.592)
  5. ^ Feuerstein, Steven; Bill Pribyl (September 1997). "Oracle PL/SQL Programming". 18.5 Modifying Persistent Objects. Retrieved 23 August 2011.{{cite web}}: CS1 maint: location (link)
  6. ^ "Performing raw SQL queries | Django documentation". Django Project. Retrieved 8 September 2024.

Read other articles:

Usia rata-rata menurut negara dalam beberapa tahun pada tahun 2017. Peningkatan jumlah generasi muda terlihat jelas di beberapa bagian Amerika Latin, Afrika, Timur Tengah, dan Asia Tenggara. Sensus Penduduk 2020 Indonesia mencatat persentase Gen Z sebesar 27,94% dari jumlah penduduk Indonesia. Generasi Z, sering disingkat menjadi Gen Z dan dalam bahasa sehari-hari dikenal sebagai zoomer,[1][2][3] adalah mereka yang lahir pada tahun 1997 hingga 2012, kelompok demografis...

 

Es kacangJenises serut AsalMalaysia Komposisies serut Bagian darihidangan Malaysia [sunting di Wikidata]lbs Air batu campur atau lebih terkenal sebagai ABC (juga dikenal sebagai es Kacang di Pulau Pinang dan Singapura) merupakan sejenis minuman yang dibuat dari es yang diserut dengang mesin dan dicampur dengan bahan-bahan seperti kacang, buah kabung, cendol, cincau, jagung, pemanis, seperti sirup dan sarsi serta air nisan. lbsMinuman beku Coolatta Daiquiri Frappuccino Margarita Orang...

 

Former association football club in Glasgow City, Scotland, UK Football clubParkheadFull nameParkhead Football ClubFounded1880Dissolved1963GroundThe SheddensHelenslea Park, GlasgowNew Helenslea Park, GlasgowLeagueGlasgow Junior League 1895–1927Scottish Intermediate League 1927–1931Central Junior League 1931–1963 Parkhead Football Club was a Scottish football club from the Parkhead district of Glasgow who played in Scottish Junior Football Association competitions from their formation in...

Mswati IIIRaja Mswati IIIRaja EswatiniBerkuasa25 April 1986 – sekarang (37 tahun, 347 hari)Penobatan25 April 1986PendahuluSobhuza IIInformasi pribadiKelahiran19 April 1968 (umur 55)Raleigh Fitkin Memorial Hospital, EswatiniWangsaDinasti DlaminiAyahSobhuza IIIbuNtfombiPasangan14 istri secara bersamaanAnak24 anak Mswati III (lahir Makhosetive Dlamini lahir 19 April 1968) (mungkin 1970) adalah Raja Eswatini dan kepala keluarga kerajaan Swazi. Pada tahun 1986 ia menggantikan ayah...

 

محمد نبيه معلومات شخصية تاريخ الميلاد 7 ديسمبر 1930 [1]  الوفاة 13 ديسمبر 2021 (91 سنة) [2]  حي العجوزة[3]  مواطنة المملكة المصرية (1930–1953) جمهورية مصر (1953–1958) الجمهورية العربية المتحدة (1958–1971) مصر (1971–2021)  الحياة العملية المهنة ممثل،  ومخرج،  ومؤلف  اللغا...

 

Drinking establishment catering to lesbians The Lexington Club (1997–2015), a.k.a. The Lex, was San Francisco's last remaining lesbian bar Part of a series onLGBT topics       LesbianGayBisexualTransgender Sexual orientation and gender Aromanticism Asexuality Gray asexuality Biology Bisexuality Pansexuality Demographics Environment Gender fluidity Gender identity Gender role Gender variance Homosexuality Intersex Non-heterosexual Non-binary gender Queer Queer h...

Halles centrales de DijonPrésentationType HallesIngénieur Louis-Clément WeinbergerHauteur 13 mPropriétaire ville de DijonPatrimonialité Inscrit MH (1975)LocalisationCommune DijonCoordonnées 47° 19′ 25″ N, 5° 02′ 23″ ELocalisation sur la carte de FranceLocalisation sur la carte de BourgogneLocalisation sur la carte de Dijonmodifier - modifier le code - modifier Wikidata Les halles centrales de Dijon sont des halles en architecture métallique ...

 

† Человек прямоходящий Научная классификация Домен:ЭукариотыЦарство:ЖивотныеПодцарство:ЭуметазоиБез ранга:Двусторонне-симметричныеБез ранга:ВторичноротыеТип:ХордовыеПодтип:ПозвоночныеИнфратип:ЧелюстноротыеНадкласс:ЧетвероногиеКлада:АмниотыКлада:Синапсиды�...

 

Pour l’article ayant un titre homophone, voir Château de la Rochefoucauld dans l'Oise. Château de La Rochefoucauld Le château vu du pont sur la Tardoire. Période ou style Renaissance Début construction XIVe siècle Fin construction XVIIe siècle Propriétaire initial Aimeri III de La Rochefoucauld Propriétaire actuel François-Alexandre,15e duc de La Rochefoucauld Destination actuelle Propriété privée Protection  Classé MH (1955)[1] Coordonnées 45° 44�...

Si ce bandeau n'est plus pertinent, retirez-le. Cliquez ici pour en savoir plus. Cet article ne s'appuie pas, ou pas assez, sur des sources secondaires ou tertiaires (juin 2013). Pour améliorer la vérifiabilité de l'article ainsi que son intérêt encyclopédique, il est nécessaire, quand des sources primaires sont citées, de les associer à des analyses faites par des sources secondaires. Carlo LottieriCarlo LottieriBiographieNaissance 6 novembre 1960 (63 ans)BresciaNationalité it...

 

British politician (1815–1895) The Right HonourableThe Lord AberdareGCB PC JP DL FRS FRHistSLord President of the CouncilIn office9 August 1873 – 21 February 1874MonarchQueen VictoriaPrime MinisterWilliam Ewart GladstonePreceded byThe Earl de Grey and RiponSucceeded byThe Duke of RichmondHome SecretaryIn office9 December 1868 – 9 August 1873MonarchQueen VictoriaPrime MinisterWilliam Ewart GladstonePreceded byGathorne HardySucceeded byRobert LoweVice...

 

SoegiartoSoegiarto saat menjabat Wali kota Yogyakarta Wali Kota YogyakartaMasa jabatan1981–1986GubernurHamengkubuwana IXPendahuluH. AhmadPenggantiDjatmikanto Danumartono Karier militerPihak IndonesiaDinas/cabang TNI Angkatan DaratPangkat Mayor Jenderal TNISatuanInfanteri (Kopassandha)Sunting kotak info • L • B Mayor Jenderal TNI (Purn) Soegiarto adalah seorang purnawirawan perwira tinggi TNI Angkatan Darat dan juga tokoh penumpas pembrontakan Gerakan 30 September 1965. Ia...

United States federal government office building in Washington, DC This article is about the current building. For the former building of the same name, see O'Neill House Office Building (1947). Not to be confused with Thomas P. O'Neill Jr. Federal Building (Boston). O'Neill House Office BuildingThe O'Neill Building just before reopening after its renovation in 2014Location within Washington, D.C.Former namesFederal Office Building No. 8General informationStatusCompletedLocationUnited States ...

 

Women's college in Clinton, New York This article is about the defunct liberal arts women's college in New York State. For other uses, see Kirkland (disambiguation). This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Kirkland College – news · newspapers · books · scholar · JSTOR (April 2009) (Learn how and when...

 

Friedrichshafen Lambang kebesaranLetak Friedrichshafen di Bodenseekreis NegaraJermanNegara bagianBaden-WürttembergWilayahTübingenKreisBodenseekreisPemerintahan • Lord MayorAndreas Brand (FW)Luas • Total69,91 km2 (2,699 sq mi)Ketinggian400 m (1,300 ft)Populasi (2021-12-31)[1] • Total61.561 • Kepadatan8,8/km2 (23/sq mi)Zona waktuWET/WMPET (UTC+1/+2)Kode pos88045–88048Kode area telepon07541, 07544Pelat...

Play by Christopher Marlowe This article is about the play by Christopher Marlowe. For other uses, see Doctor Faustus. The Tragical History of the Life and Death of Doctor FaustusFrontispiece to a 1620 printing of Doctor Faustus showing Faustus conjuring Mephistophilis. The spelling Histoy is agreed to be a typographical error.[1]Written byChristopher MarloweCharactersDoctor Faustus Lucifer Mephistophilis Belzebub Seven deadly sins Pope Adrian VI Charles V Duke of Saxony Helen of Troy...

 

American prospector and businessman This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Obadiah Bush – news · newspapers · books · scholar · JSTOR (October 2015) (Learn how and when to remove this message) Obadiah BushBornObadiah Newcomb Bush(1797-01-28)January 28, 1797Penfield, New York, U.S.DiedFebruary 9, 185...

 

Yukuhashi 行橋市Kota BenderaLambangLocation of Yukuhashi in Fukuoka PrefectureNegara JepangWilayahKyūshūPrefektur FukuokaPemerintahan • WalikotaJun TanakaLuas • Total70,0 km2 (300 sq mi)Populasi (Oktober 1, 2015) • Total70.586 • Kepadatan1.008/km2 (2,610/sq mi)Zona waktuUTC+9 (Waktu Standar Jepang)Simbol • PohonOsmanthus fragrans• BungaCosmosSitus webSitus web resmi Yukuhashi (行橋市code: ja is...

StioKomuneComune di StioLokasi Stio di Provinsi SalernoNegaraItaliaWilayah CampaniaProvinsiSalerno (SA)Luas[1] • Total24,28 km2 (9,37 sq mi)Ketinggian[2]675 m (2,215 ft)Populasi (2016)[3] • Total942 • Kepadatan39/km2 (100/sq mi)Zona waktuUTC+1 (CET) • Musim panas (DST)UTC+2 (CEST)Kode pos84075Kode area telepon0974Situs webhttp://www.comune.stio.sa.it Stio adalah sebuah kota dan komune ya...

 

District in Kampong Speu, CambodiaSamraong Tong ស្រុកសំរោងទូងDistrict (srok)Samraong TongLocation in CambodiaCoordinates: 11°28′N 104°32′E / 11.467°N 104.533°E / 11.467; 104.533Country CambodiaProvinceKampong SpeuCommunes15Villages294Population (1998)[1] • Total74,651Time zone+7Geocode0507Samraong Tong District (Khmer: ស្រុកសំរោងទូង) is a district located in Kampong Speu Province ...