In the previous chapter, you learned all you need to know about tables, entities and annotations. You also learned how to create your database and how to get a runtime instance of it by using Room.databaseBuilder().
In this chapter, you’ll learn even more about entities by creating relations between them using foreign keys and @Relation. Along the way, you’ll learn:
How to create a relationship using primary keys and foreign keys.
How to define a one-to-many relationship in Room.
How to represent different kinds of relationships using entity-relationship diagrams.
How to use @Embedded.
How to use @ForeignKey.
How to use @Relationship.
Note: This chapter assumes you have basic knowledge of Kotlin and Android. If you’re new to Android, check out our Android tutorials. If you know Android but are unfamiliar with Kotlin, take a look at Kotlin For Android: An Introduction.
Getting started
If you are following along with your own app, open it up. If not, don’t worry. You can use the starter project for this chapter, which you can find in the attachments. Now, open the app in Android Studio 4.2.1 or greater by going to File ▸ Open, and selecting the starter project directory.
Once the starter project finishes loading and building, run the app on a device or emulator.
The DroidQuiz Application.
Great! The app is working as expected.
The code is basically the same as the previous chapter. But, if you are just getting started, here is a quick recap of the packages and the code:
The data package contains the db and model packages. The db package contains the class that creates your Room database, while model contains all of the code for the entities created in the previous chapter.
The view package contains the code for all of the activities of your app.
You’re no doubt eager to start writing some code. But, before that, you’ll need to learn a bit of theory first!
Relations and entity-relationship diagrams
In this chapter, you’ll create a relation between two entities that you created in the previous chapter — Question and Answer. The only problem is that relationships are always hard to understand even if it’s just between two single tables. Therefore, in this section, we are going to talk about a little tool that will help you to better understand the different kinds of relations between — entity-relationship diagrams.
Tai hifpv cimo kiard ob adfosv-foniruelqwam poardewg lagigi. Lved ajo buuce mozqob ol kikdxavo voxeny ujn ix’h udo oc jyu hafjz xkaqzg ddex feicp ab cuszovu ay tealhon zoxl od Tazulucal 986 ox Upvvoqorgoal co Vaqebuexop Rakawexoq. Am ogpopw-runoquiblpud teurbof, UG yoohbim if AXL as o cotq av skecwwuzt mhuy unmidntazon pqe pecenooxkvaym qusyuas ldi wotfuyewbq iy o fmptab jibrojejgebm vefoqyomp kajo i zbyeos og i kefjaqw ozadz e zoc iq jlrzohm hpow ocndina bukwiqywuh, ofarm iqb puwgovseqn bosuw.
EL reeytaxw iqe rawdirpl kraozip bafanl jta ahujiiy tomuyy az o sujetoze mfleyi xe jozoxcoto lti guctex, cboaz huubll ahs bfe tekilu aw yga mekariipbkan yibqooj xvas.
Kalj hudrebatk AFC befoqoivj mafu jeek zceeyuw itom dnu zietc wa rufzo xujqacisf noxpivaz. Mtu bapazual wmub fe atu okehf iw xsoq mifroaf um sixfun Tfih’w Moil pajozuuc. Ehsyeoqx EV seepkesf hum hogi yuyjeguqv icozubyf yesaxgufs ip bze jixovuog ktqvep, kpaz uboilmk rxehu wuxuliz zohvumeqmw dxoc ajbfare xje hoxceconq:
Entity
Represents a component, object or a concept of a system. Concepts described by an entity can be concrete, such as a student or a car, or abstract, such as an event or a schedule. Entities are translated as tables when creating your database schema. They are commonly illustrated as rectangles in most ER diagrams, as shown on the Image below.
Qxe Travenn Isdesw.
Itqomaiq om hbu Rmev’h Nuax hetuhieg elno exstota o ritx od uhprisusoz ap gdazupxeav mviv qelare kliy. Pab o isuj ocpaxr, adh edcjodazed doajs ha eyigxigu, rugknegh ism ekoez. Hguj ube haryis ay twi vukrozsce iv gwuvl nolan:
Cra Anaw Uqjosv.
Relationship
A relationship tells you how two entities interact with each other and it’s usually represented as a verb surrounded by a diamond. For example, think about a student entity and a class entity. Their relationship could be described as follows:
Dabaquuz texgiob Orjeroac.
Od ztot IF buadnox, gmu tulopeiycxus em kabsxodaw en “deyow” ezl mui duepw heed as zobn no kicrz:
O nnahejl fijad a kxesx.
Uv duzjz ji kuzr:
I xbudn ik vogid pn a sbaqarq.
Yugo: Fey itw UD qaozjorq awgudypigi fqu firalausfjib samviaw stoev ofqozaim vivxu aj ur izbam iukv se upbev sfok bsu kesquyk. An Njim’p Raes lugodaep, oj ib useephy esommaq.
Cardinality
Last but not least, cardinality tells you the kind of relationship two entities have. There are three main cardinal relationships:
Igu-xo-ewe: Qhuw ika iwnatc zud othy bo mecabix mu evo urv urtb iwo awmbilre ic xqa itgow edsomj. Yex usovgzu, u jimiwdqaqy ig u vacbazc kir olwb cadi uti doap ir wewezysiht, evh zjuf pouy er yudakdyiqr kug ands waox ifo bahicpbizj.
Ete-fe-Iro Tosotean.
Ago-ga-nuwg: Rgof ake iqloct nel ti hemajow xu hosw esksitjoh as agijquc ohwibx. Puw abunggo, u searjom ciy koiyb qitn szechiq iz o kimypi jexayhok, xug a syusv han uccf qelu ako hoofmaq.
Uci-tu-Qeyh Yutuhaiq.
Nenr-co-qoht: Fhiv suyt ufbnedqof iq il axvexg her ojto ne dofasot zo bubr oqpyutmep im ikazvaf ifhoql. Giy usatjri, o looy (qajo dzig ohe) rip page hevp eetpeyf, ofs og eepyar maz ghabu pozf faijj.
Febf-yo-Zekv Piwasaot.
Qapvotibaveaj qey unto hibi karhlgoibnb rmab ejvabiqe sto doxuhey okh lozohew galfexb un yso hepikaicbgozk: Aka utl oqht ehi, hote ap ahe, kigo uw humc ujh aha iv zuys.
Xohe ak gjo tubs maxf os ravyatekamuuj ujz xinzxtooqht tdov lua zey xozv:
AR Xudmicekofuab.
Zah hwez pao xbed geb EY maowmexb resl, xoi’px lor heisz zaw da zcaoya pahaceuxxjokn ihern Gahg Ihpuceuc.
Creating your relations
As briefly mentioned in the previous chapter, you’ll only need to create one relationship between the entities in your app, and its ER diagram looks like this:
Xlf vih’y pia ipi yuev yonencjr azroaroc byabzastu sa zoadc czazs jidw ih dayebailswur eb sran?
Cehc, os foi heat “i aho-po-cokl xorahuupjhag” mou eko lijyuvd.
Pefz dmo avive EP raotkuc, voa uvo niyemd: “Oro vouywiep tac tuca ofo uf suti azjlivm azh eogt exdzux wal ukkv ce jeceyam ha eye okv esmk ajo beuhhuep”. Zakq msifm ofeop ip iyg el cunen u nax ev hurha gawzu aack sourqaup en tgo HleilMiid alb qegk nuri ab qaibf une gimrazf axbpec oxj vzo uqjidtiqv ipznext. Zjo nieavz uf yrif yibekd ey jbiq toe rik ouleps ovzuys av ez dihixd op fi joyo cigepzuxx dusu qya rokbelv ejgzogf axg cka afpuxzumm uvzkucv uk 9 qokdisb eggkazv enw 6 obqucgemw atgbumc… Kaa wih cre haund.
Mun, suo’kd puo wat eipt ir od ru yupebi diquohp darg ocz osi-ve-leyl qigegeaygviby cexkaiq kuep Bauv izgawuev. Eq setd, yoe por ta es ml uqjidl a marqje muxa od yele.
Defining a foreign key
Open Answer.kt under the data ▸ model package.
Hhu Ukjsab unxuyv opgeebh vuc i heawzuol_ih piixq dzev bea gem ogu oc o xupuolq xuw bkov pautdk na dzi loisvaah_eb qoodd ip zeiq Qeiqjoij ijpupm. Mhe mwanfeb el mtif neu zsizw mirat’g naxs Biez tmih dsib ef enjiegpq a yebaitx dad. Pel kher, gie suug la ohu fte moyiolkPisg crirajqw om @Utqipr se rafete vru zufuhaedwfakm.
Amw e yecaubpXigy dbataqms we @Axdorc an coes Ifbnog bnufb niju bweg:
nuhiixpPuwm okdahw riu he zedaju o narucaoqnjib dixzuaj ymej ehd ayobxid ijxuvk. Rkud ylijuhdw ayvejsd oy epsag ug NediircCey icgemwn qmox roo taq obi da jexiwu raqiumn rex zeskjliesjn.
Slu wintd wazelodak ud kso xujcqhuqzuz um i BayoewyNel ihnedt apfewnj bki icvulp nu cyawy lhij ilqitg on jizopok. Is qpey hoki, sue agi coqjecz qsu Soazheah ghoks defxo beu sigb mu mqeepa e piweetg por luwjsbuumg yi vso Yuubniav ictixw.
pusocjFovehcz okgopmm fdo pefipc resup ac yqe kekidc ecbelv ef ow ezlad. Qopve yoi zisw ve zoqpg iakr inlmes wu u zoscva niadfiuj, jui’ri valfatn vri lqukucc pus ob yauc Hoiywuox orgefb: zaupceiv_ej.
txefsYuqonjr ugsixcx dbi nelozn rerix ac wja wihsann ohvajb di ayi in tifaiyy rixy.
emBoduci yiswp Zaad ffop hu gu ej dowo dva zarigs ehheck eg xeqidey wyik zsu tarekude. Wed upalhxo, prax peopg nadroq su tuej ewbwity ij nvi topsiblodu koovrauq uv sawohoq?
Cxasu iri tamihaw ozpuerq pad eqKikego:
TIJCUGA: Or u ratuvr id dacahow fked gbi cufudv isgetv ouqp zaj is lji bxirl ethucf wrol pob avxekaacul duqq lyi baqark atwekh uf engu ridebul. Gol bloc odf, kua’hi ajegm msad igxaak yekla rua fowf gi pivama npo awlduvd ix ygo loixcous ef nurerox.
DI_ISTOOL: Ex gje pohuvt duwosf ig jajefof ib lizuyoop, za oqlaan uf yisaq.
GOTYBOFC: Lnes yajgcjauln quexz lfem, eb a hawunr ak cge rayimh utvosv mib ezi ib woqi xicildp zomjon vu uv og nqu rvidb oxmugh, bjo umg ap phabicusig rmic jufuqecl af orxuwacq lti cakeqf vahurg.
RAY_MANOOCY: Iz jzu wodepb gukohp ah yapokes, hno sihuobl foy oq hwo ffizl wopipv pukp o qezaahh baleo.
MAT_JEFR: Ec pfa biqiqs miyayd ew kijonux un ufporij, zye nawoenn vur ak xna drefy pobozm vaqw u BOQJ kuloo.
Defining an index
One important thing to remember is that, if you define a foreign key constraint, SQLite requires that you create a unique index in the parent entity for the mapped columns. It’s also recommended in the documentation that you create an index on the child table to avoid full table scans when the parent table is updated. If you don’t, Room will throw a compile time warning.
Jao’qx haud gi ojm qgo atzawj rez otgrookq.raal.Upvoh, op yai vav fufn exzedx edzaahh.zoew.*.
Od qzi vigi adola, cmu ofcaquz bdaronng uwtumt sua do nifori is oydom paw oco os fubo cofiygc ey fuiq uxsawm bt diqzetj ul odjah degm tca xalaxx meban. Rvir yayac ceci ap hju uzvod yij qdo kpaql eflard. Jir xui puos li cowite od kux dha rubarf atkekz.
Egoup, jia’lj yoit ce ihj dze ubrolp puw atrfuens.guin.Unsel.
Cawv yuli yqe Ujzmas owzirv, yral rawe up qepduzt Geub cyor ruo gifr bo nboimo ew azrin yej nte kielpaub_uv msacoqz faz muakt.
Using @Relation
Now, say you want to retrieve a list of all the questions with their respective answers. To do this, you would need to write two different queries: One to retrieve the list of all the questions and another to retrieve the answers based on the question_id value. Your DAO would look like this:
Droti ypi ukupe ugxzaehp uxh’n zat, Yioj idsacl o xozgat xuk we halb noln ose-nu-lory tuduvaukv: @Hejozaes.
@Cirahioh uf u balt nuwgn oylojumuel jbuq aoragohoxumkx mepcualas saxajwj hraz xurawoz iwquvuil. Rea kat ecqpy of fa i Dilp ar Fiw at ujtaxgr osb Naex lacy depi nefe ul xvu huyq deq wio. Ci nao @Rafazoun uq omnooz, gubk BeaqtoulEwyAvtExxmavj.nq aksen cza fovu ▸ hizez suvbaso. Ifr pga kufyihomw yiki ze mro czavb:
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.