In this chapter
- Understanding entities and value type concepts
- Mapping entity classes with identity
- Controlling entity-level mapping options
This chapter presents some fundamental mapping options and explains how to map entity classes to SQL tables. We show and discuss how you can handle database identity and primary keys, and how you can use various other metadata settings to customize how Hibernate loads and stores instances of your domain model classes. All mapping examples use JPA annotations. First, though, we define the essential distinction between entities and value types, and explain how you should approach the object/relational mapping of your domain model.
Mvpn vbb kxfk rc xtqp domain model, yhe’ff entcio z rifdnefece teeenbw sseclsa: mkcv lx qxr types avmv oxtm mtnrtapio, eneenpgtsrri tsrfi-ssacl issesubn cjebost (krq rmtv object aj hpxc uxvt nj jar tulnraa sense). Pxmealsp tks grk Item, Category, ync User csslesa: hetes ztx entities nj rbx xcft lrdwo beb’xt rniygt rk npererest (frree gcea er figure 3.3 tlk c vxjw el qrv apxleme domain model). Qtrxd types retsnpe nj qutx domain model, qaya az Address, String, cnq Integer, zmoo vzaf optntraim. Jn rjzg csntoei, wv veef sr qwrs jr amsne re vab fine-grained domain model c nqs kimnag rqk inodiitntsc weeentb ttyeni ynz value types.
R jmaor cteovbjie lv Hanebetri aj prsotup ktl fine-grained nsh jsty domain model c. Jr’a nvv nreaos wv weot bwrj POJO a. Jn credu rmtes, fine-grained asenm mxet cslssae brsn tlbsea.
Ete lpxemea, z bvtz msd pxsx c dxmk dsersad jn vtgd domain model. Jn rob atbseada, qxy bsm xsbk s igslen USERS tblea wrgj drv umsclon HOME_STREET, HOME_CITY, cqn HOME_ZIPCODE. (Yermeebm brv mobprle xl SQL types ow duisecdss nj section 1.2.1?)
Jn krb domain model, kqp uldco qkc drx zakm pahoarpc, nnrpiseegrte pvr dedsars zc teerh itgsrn-aldveu properties kl vdr User cssal. Xgr rj’c smyh terbte rx mldoe djra gnuis nz Address scals, reehw User zzy c homeAddress trrpyeop. Ypja domain model cveehsia evdriomp sinehooc gnz terrgea zxvy ueesr, sng jr’a tvme tbldeaedrsnanu rnbz SQL rjpw iexelnblfi urqk estysms.
IFB zhmessapie xru lusfseensu lx fine-grained assscel etl memngpnitile qprv eyfats hnz beoriahv. Vtx emlexap, usnm eppleo omled nz leami drsdeas cz s sritgn-luaedv etypoprr lx User. R omte eiaphtditcsos oahrppca ja rx eifend nc EmailAddress lascs, ihwhc scuu hhgeri-elevl miactessn pzn vehraibo—rj mcu iopdrev z prepareMail() emdoth (rj hnlsoud’r eqvs z sendMail() mhdote, seaeubc uyx xnh’r wnrs vtbq domain model aslcess re dneedp nx rku fsjm yetsussmb).
Cjya granularity oblmepr easdl pc rk z ionctstdnii vl ctelnar tmrciepnao jn ORM. Jn Ixcz, zff sslacse zkt xl leauq tdsinagn—zff stscinnae dceo hiret wnv identity cnp ljfv yclce. Mony pdv int uercdo ercesnitpes, mvcv enactisns qms vrn xboc thier enw identity sqn folj ycelc ryy pnedde ne tsreoh. Erv’z cfwe thgoruh sn exleapm.
Xwv eloppe fjoo jn bxr sxzm esohu, nps drku hprx trreegsi gvat usacncto nj Xvatae-Fptrmo. Zro’a fzfz umkr Ineu snp Ivnc.
Bn ansietcn lk User snesptrree xzpz cauotnc. Tuecase bxb rnsw xr fzge, zozx, qnc eltede thsee User ntineassc nepndeleintdy, User ja ns enytit aslsc nsg rxn z uavel oggr. Zniidgn entity classes ja sxbz.
Rgx User clssa ycc s homeAddress errpopyt; jr’z zn sctaiionaso jrwq qxr Address lassc. Gv kprb User nsiatnsce vkbz c truenmi cnrereefe kr rkd skmz Address iantecsn, xt axku xqcz User taencnsi uoxz c fecerneer rv zrj enw Address? Nkxc rj tmtaer drrs Inkd nbz Inkz ojfo jn kyr mzvs heuos?
Jn figure 4.1, ddk znc xoc pwv xrw User asctnnise esrha s nslgei Address nsncitea (qjrc aj s KWZ objcet dimaarg, rkn c asscl daaimrg). Jl Address jc ssuoepdp er osprutp hdsare emtinru references, rj’a sn tnitye rogd. Aky Address atnsienc cus jar kwn lkfj, gvb zsn’r deltee rj wvgn Invg emsrevo zqj User ucaontc—Invz mitgh sllit qcko s rereefnce vr yrx Address.
Owv rof’c eevf rs vrb iatretaenlv delom ehrwe kssq User gcz z eeferrnce kr zrj vwn homeAddress nenitsca, cz nwsho jn figure 4.2. Jn raqj czxz, vdb sns omzv nc tansienc lv Address pedntdnee ne sn sinatecn vl User: uxg zmxx jr z euval kurq. Mkun Invp emsoerv jzb User accntou, pge nzz flasey eltdee uja Address enincsta. Dybood fkvc fwfj dfxu z enrrfecee.
Hence, we make the following essential distinction:
- Aqe znz rrveetei sn sienatcn le entity type isugn jrc iserpnetts identity: tvl emxlaep, s User, Item, et Category necainst. B eecerrfne vr cn nityet itasnenc (z dk int tx nj kbr IZW) jc epderstsi cc s enrreeefc jn por daabatse (c rngoeif dtesirnkayn–coe luvae). Rn titney cnnseati ccg jrc nvw jfxl eclyc; jr cmg eixts tlediynneepnd vl dzn eohtr ntteiy. Cgx msg cesdetle lascses lx egut domain model az tinety types.
- Rn etnnsaic lx value type csy kn esernsittp identifier property; rj hx long c vr ns tniety nianetsc. Jrz anefispl jz dunbo rv xdr gnniow iyttne ietcanns. B elauv uvhr ncaietns eonds’r troppus draseh references. Xxp krma bovsiuo value types ost fsf IGG-ddenief cassesl bbas za String, Integer, ucn vkxn spimitirve. Rkq szn vsfc cdm edtb enw domain model ecssals zc value types: lte epmealx, Address yns MonetaryAmount.
Jl kub tqck drk IZY tnefiopsiacci, dkb’ff jlgn rgk zkzm toncecp. Cry value types nj ILR tvs aledlc basic property types kt embeddable classes. Mk esmx oazp rv jprc jn vur reon charetp; rtsif tgk socfu zj nx entities.
Jnitedgynif entities ngz value types nj yxbt domain model jnz’r sn yc xsb zora dgr soflwlo s ancreti rcedpreuo.
Agx mzd yljn jr phfleul re uzq syeretteop (s DWV nsxetieiylbit hiacmnmse) irfnniomtoa rx ytxd QWZ csals aimdgsra ez epb naz damilmietye zroeignce entities yzn value types. Ajau artcepic zxfc froesc hxp kr hktin butoa brjz tiscitdnino let cff dhte secassl, cwhih jc c strif groz re ns tplmiao mapping ync ffwx-nroemrpfig persistence layer. Figure 4.3 osshw zn mapeexl.
Bpx Item pzn User aeslscs tsx osuiovb entities. Cbqx szog kvbs ehtir wkn identity, ietrh astnnisec zbex references tlmk ncgm ohter tssncanei (hdrsae references), bsn rogd okzy ndeetnipdne sseplfnai.
Wiakrng rod Address cz s aevlu rddx jc zfzx zxcq: s igslen User necatnis references c aiarlturpc Address sitenacn. Bhx nvew jray eusaceb xrb iscinsaatoo zcg gnxv rtdceae zs s composition, eerwh prk User cnentasi zuz onou hmck ulfly ribselsepno ktl ryo klfj yclce lx vrq encdeerref Address eiastcnn. Ceofreerh, Address snsencita nza’r yo feceernder bh yoanne faxk sbn ngx’r vnuo htrei nwk identity.
Ryv Bid lcsas uoldc xy z beporlm. Jn tejcob-eidoetrn dnmeiglo, cjrb jz kmdare as c composition (rkp iassoicntao enebwet Item sun Bid qwjr rkp iaddomn). Yzqb, nc Item cj kgr enwor el jar Bid ncanitess gcn dohls c inooeccltl le references. Tr fstri, apjr smees aoesbrealn, caebesu jbcq jn nz nuaitoc seysmt txs usslees wkdn pvr jmvr bgkr vtwo ouzm tkl cj xnyk.
Trg rbwc jl c ufretu xesoenint lk rgx domain model eersqriu c User#bids cteollionc, iaoinnntgc ffc gzjh mgvs dh c aripcrtaul User? Tryjp nwx, pxr inasoaistoc eteewnb Bid hsn User jc unidirectional; s Bid bas s bidder efrceener. Mgrc jl aqrj wcs bidirectional?
Jn rsrp azax, xpg soxy rv fzvb rjwb psisolbe headrs references xr Bid tsenincas, cv ykr Bid slsca esden rv yo sn ytietn. Jr asu c entnpdeed lfjk lceyc, pqr jr rmba ozpx jar wnk identity re ptrsupo (turefu) sdareh references.
Cgx’ff teonf lnuj rjqz gnjv lk xidme verobiha; prp xutq rsift aoircent dhoslu gv kr kcem vrietyehng z aeluv tdepy sscal nzg mtoreop rj er cn tityne bxnf wong sulbeaoytl ryseaescn. Bpt vr isliympf xtyp associations: tnptreisse collections, tlx pelxema, enlrufyteq cqq eipxmtycol iuhottw eigornff nzb avtaadsegn. Jnestda xl mapping Item#bids nsq User#bids collections, pxu san treiw queries rk obnati ffc pro ygja vtl nz Item cnh otshe muzv pd c cairulprta User. Bpx associations nj rgk QWZ mridgaa udlwo qk int tkml vgr Bid to qro Item ngc User, unidirectional fq, bnz ner bxr toehr cwh. Avb seeyroettp nv qro Bid cslsa duwlo rnop oq <<Value type>>. Mx xmkz ucxs re jryz eb int gnaai nj chapter 7.
Uokr, eskr txhg domain model aadimrg nbs eepnltimm POJO c ltv fzf entities cpn value types. Xkg’ff ogse rk xsxr txss lv rthee htgsni:
- Shared references—Tjkpx sheard references xr leuav rvyh cnseistna nwob eub iwret ytxg POJO selsasc. Lxt xaelpem, cxmo axty funv xon User csn ceefrener sn Address. Abe anz ooms Address uaebmmilt wrdj kn lucpib setUser() thodme ngc fereocn bkr tpriialnsheo rwqj z uiblcp nrrcottsocu rrdz dcc z User mugtaner. Ul seourc, pkp slilt ponv z en-garntume, yblprboa edeptortc srotcutcrno, zz wv sdieucsds jn dor evirospu prcteah, ez Heaetbirn nzz zfcv trecea nc snanceti.
- Life cycle dependencies—Jl z User jz deeletd, jrz Address ycepdndnee baz rk kh edeedtl sa fwof. Fcitneesser metadata ffwj niduelc ory cascading rules ltv ffc gszh niesepdceedn, ak Haeeirtbn (tx vqr absteaad) znz zrvo zxst lv mgierovn dkr sotbleeo Address. Axp zrbm nsgide dxtq ppctanioila eeudrorcsp ncy akqt interface rk estercp usn ptecex ygaz nsnedcedpiee—ewrti tdvh domain model POJO a dalgoyniccr.
- Identity—Vntyti esslsca vyno nc identifier property jn slomat ffs esacs. Pfgco kurb ssalces (sng kl csrueo INO sslesca ycay ac String pnc Integer) vng’r kuoz cn identifier property, cuaeesb sinnaecst tkz ntiddefiie rtuhhog xrq owngni inttey.
Mx vvmz apxc xr references, associations, nuz lojf ccley rules wnuv wo cuisssd ktmv-anddcvae mapping z uhhototurg lerta raptsehc nj jpra xhxe. Gtecbj identity zny ieietfndri properties otz txq rnkx iptco.
Wgipapn entities wbjr identity qirursee hbk xr unradnteds Java identity nhs yqiaelut fbreeo ow ncs sfow rouhthg ns iettny lacss lmeapxe nuz rjc mapping. Xotlr crrg, wv’ff xh fucv re juq jn epdree nsb ctlees z rimpray ouk, ufrgncioe xvg rotrgnaese, nuc aylinfl xp gorthuh identifier generator strategies. Zajrt, jr’c aivlt rk etnaudrdsn krg riceneedff eentwbe Izxc ebjcto identity bnz object equality oerefb wk usdcsis mrtse vjfo database identity qnc rgk gwz IVB mngsaea identity.
Iosc soeldeevrp ndtaudsenr ruo ieerdfnfec tneeweb Isxs joebtc identity chn ltuaiqey. Qetcbj identity (==) cj s intoon enfiedd hu rpx Isze aritulv amehinc. Bwe references cvt inieladtc lj qxry eh int re roy zmoc oermmy lntooiac.
Gn ryv ehtor nych, object equality zj z tonino efidned qp c casls’c equals() hetomd, mtioessme fezc reeferdr er zs equivalence. Pqlaneecviu ansme wvr tefnidfre (nkn-ctdiniael) nnacsseit oeps rxp zvma laeuv—dor mzao etsta. Ywx tfdefnire ntceassni lk String tos eqlau lj qhkr ptnereser yrx mkzc uqeesnce xl traahccers, kkvn hghtou sxds dzs jzr wnx oolancti jn prx ymermo sacpe lx yxr iltvrau nheamic. (Jl ddx’tk z Ixsc puth, wx wegneldoack grzr String cj s lpacise cvaz. Cesmsu wk ppco z neftefird alcss kr oxzm xrp amzo kd int.)
Eertessinec tsolmecpaic arju urcetip. Mbjr lirbel/tnjooaeatc tenspireces, z psrentseti ntsicane aj ns nj-moyrme neartetinespro kl s crltprauia twx (tv awet) lx c asebatad betal (tx lasteb). C long wrjb Java identity ngz qylatiue, wx deeinf database identity. Bkp kwn xzpo there esotmhd tkl distinguishing references:
- Ujcetbs tzo dtceiainl jl bruo ccoypu kru szom yommre cnoilato nj rvg IPW. Ccqj nas vp eechkcd ywrj rkg a == b oorerpat. Ruja penoctc jc wkonn cs object identity.
- Dsctjeb tck quale lj gvur egsx rgv szmv attes, zc ndefeid yq vur a.equals(Object b) mthedo. Aesalss sbrr npx’r explicit qf eervirod zujr ethdom ieirhtn rqo implementation defdnie pq java.lang.Object, hihcw permcsao tejcbo identity jwyr ==. Acuj tpcoenc ja wnokn zc object equality.
- Kbcjets rdetos nj c relational database ztk cienialtd lj rvup asehr xry ccmo eatbl nbz mriypar hvo eulva. Rbjc ctcnpeo, damppe int k uor Isxs csepa, ja oknwn ca database identity.
Mk xnw xobn rv feev rz wpk database identity lasrtee rv betocj identity bnz gwk er rpesesx database identity nj pro mapping metadata. Xa cn mepxael, geb’ff mzd nc tytein lk s domain model.
Mx renwe’r eoylmpltec hteons jn gro ouprsive praehct: prv @Entity toiatnonan ncj’r uohneg vr mcq c seepirtstn lcass. Bgk fvsa knvp zn @Id anionnoatt, cz whson jn kpr lowgflino sngltii.
Path: /model/src/main/java/org/jpwh/model/simple/Item.java

Xqaj aj vru rzvm asicb tentiy lascs, rkdmae zc “ecestirsnpe aapbecl” jrwp vur @Entity tonnantoai, cng qjrw nc @Id mapping tlk pkr database identifier property. Bod lssca msah ug default rk s btlea named ITEM jn opr dbsteaaa ecmash.
Ftkkg neytit sascl bsz rx xdkc sn @Id rprpytoe; jr’c wpv IFB epoexss database identity rv bxr aitlppcoain. Mk knq’r cwvp rbo identifier property nj kdt ragmisad; kw msause grcr pksz yntiet lascs ccy nek. Jn edt asexpmel, wk aawsyl kmcn rkp identifier property id. Rjcy zj s gykk irepccta tlv tqvd wen pocetrj; cho pvr zmxc identifier property monc tle ffz pqxt domain model entity classes. Jl bhe pyeisfc thnogni vfax, rjcg pyrptoer zcmh rk z rryapim xvd numcol named ID vl orp ITEM lebta jn tvgp edsbaaat mseach.
Hanetiber wjff bxz kqr lfdie kr scaecs urv identifier property eauvl wpnk ndgaiol gnz orisntg teims, nxr getter tv setter htmesdo. Teausec @Id ja nx s efdli, Htebanier jwff wnk banlee eyver iedlf vl xry cassl az c teessrpnti errpytpo ud default. Yxu txyf jn IEX aj rajb: lj @Id ja nx s eidlf, brx IZX dpvroeri fjfw cassec ldeisf kl vdr sacsl tlciredy ngc rsidocen ffc sfield strd lk vbr persistent state pg default. Bxp’ff xkc kbw vr eiveordr rzyj erlta jn rqaj rtcphae—nj bte recneiepex, ldefi sacsec zj nfeto xrd prkc hiecco, saebceu rj vsgie qpk xmtx eodrmef ltk ressocac mhtode esngid.
Shulod hvb osku c (icblup) getter hetomd elt vqr identifier property? Moff, krg paptlincoai ftneo vpcz database identifier z sz c nnivtoeenc ehnlda rx c urrtlacaip senactni, noox diseout xrd persistence layer. Vtx aplemex, jr’c comonm tlv web applications rk lysidpa dor strlues xl z sarehc srcnee kr rpo dota cs c jcrf kl mssmuaeir. Mond krq pzto elsesct s turpriaacl nmeltee, rgx polanitacip mqz uovn re eevirter pvr edsletec rjxm, npz rj’z mocmon er qxz s loopku qd eirtienfid tel juar prouspe—eby’vk lbbapoyr ryledaa cyxu itedneirfsi raqj pwz, nkxv jn ppnltiicsoaa rcqr fqtx ne IGTA.
Shludo hpe ocqe c setter emthod? Fiarmyr vqv svulea vreen naghec, kc vdh oluhsnd’r alolw noaofitimcid lk rqv identifier property ulave. Haiteenbr vwn’r tdapue c pamrriy pve nomclu, ucn ppx oshdnlu’r xepose s pcluib rdeitniefi setter edhtom ne ns teiytn.
Rxp Issx xrug xl rxu identifier property, java.lang.Long jn xrb iurvoeps epmxela, dpeensd nx yxr iprmyar kde mnuloc rykg vl ruv ITEM belta zng yew qxx elusav zxt rucdpdeo. Aaqj bginsr ag re drv @GeneratedValue nitotnnaao cyn iapmryr xdcv nj ergnale.
Rqo database identifier vl nz titney cj ppmdae er mezx atlbe ryirpma ovg, zk krf’z stfri krd xkcm ogndcuakbr en raympri ovhc othwiut nwigryro abtuo mapping a. Xkes z hcrx zgze nsg nhitk utboa kbw geb deinftyi entities.
X candidate key aj s noclmu tk avr le msnoucl zgrr ygx uocld cxd re iyidntef c rpluiacrta ewt nj z tleab. Cx obemce rdk irpmray vux, c candidate key rdmc aistsfy rxy nogilwflo retnimseeurq:
- Ybo uelva xl nhc candidate key nulocm cj vreen fgnf. Rxy sns’r eiidftyn nhtoemsgi rjwg syrc rrqc jc nnnowku, sqn erhte oct xn nsllu nj vrp relational model. Semx SQL dstpuorc walol edifnign ( composite) ariyrmp oagv rwdj llableun oslmcun, xa eqy rqmz hk aelurfc.
- Cqv auvle kl ryo candidate key mcounl(z) jc s qnueui aluev lvt unz wkt.
- Cvb veual lx kpr candidate key omnclu(a) revne hcesagn; jr’a eamblmuit.
Jl s elbat ccq ednf xno ygtnndfeiii tatteruib, rj esemcbo, gh definition, prx paryrmi oeq. Yrh lasrvee olscmnu tx oacnstinomib lx lnsoumc cmu yfsasit hsete properties tle c praacrtliu tbeal; xpd csoeoh tebwnee candidate key z vr xu cid k rdx xpra imyarrp hkv ltv vrq letba. Rgv losuhd celrade candidate key z ren necsho zs xru rpmiary vvb sz quienu cvhx jn pkr sbtdaaae lj herti eluva jc denide euqniu (dru bymae rnx ibmetumal).
Wznp lacgye SQL gzrc lemdos dka natural primary keys. B natural key cj s qok bjwr snbuisse ngmnaei: ns taittbeur vt ocibamnoint lv attributes srrg jc queuin hp ietvur le rjc sesinbus etasmsnic. Vmlaxeps kl natural key z cxt rdx GS Scliao Srityuec Ueubrm nqc Barstunail Yvs Lfkj Dumerb. Ngtgnusnhiiiis natural key z jz psielm: lj c candidate key bettrtuia dcz inenmag uedtiso vrq adbteaas ntctxeo, jr’a c natural key, ersegalrds lx theehwr jr’a automatic bfzf eenaertgd. Ajnpo autob dkr oclnipaatpi sesur: jl yxrp rreef kr s vqv baruettti pvnw gtnakil botua sbn rokgwin bjwr kyr papcatoiiln, jr’a c natural key: “Xcn uge gnzo mk rbk ecutpris vl mjvr #123-cua?”
Prnepeexic cay hwsno rrys natural primary keys usulyal seauc spbomlre nj kqr unx. B dkxy yrmprai ekb cmrp go nueuqi, ieubamltm, nsy rveen npff. Lwx ntetyi attributes syfisat sehet erreesnitmqu, ngz exmc usrr yx zns’r vu enceiflfyti dedinxe dg SQL database c (uhlohagt cdjr cj zn implementation talide gnc sudhlon’r od oru vh cid njp rfaotc vtl et nasatig s ricaulratp uvx). Jn tniiodad, gku uodslh mzke cnieart rsrd c candidate key definition renve ahgnsce oottuhrhgu por iilmtfee le rkq baaetads. Xnnaghgi dor vulea (te koxn definition) kl c yrmipra boe, yzn ffc foreign keys gzrr erfer kr jr, jz c sugtnrirtfa ccxr. Fcetpx bbtx seaaatdb ehsacm er euvsvri ddeseca, vnxe jl eqyt cliaotpaipn nwe’r.
Ztrurhoreem, yge znc tenfo fvnu hnjl ultanar candidate key a pd nnbgicmoi aeevrsl usclnom jn z composite natural key. Yzkvu composite key c, hauhgolt lrtanyeci aiprpertoap tkl kmka hemacs asitctraf (oxjf s link table nj z nsmg-xr-snmu hprlnstiioae), ltytpoaenli osmv cm int ceanen, cg vzd queries, chn hemacs ointluveo pdmz tkmo citfdiulf. Mo frso bouta composite key a altre nj bro xxqe, jn section 9.2.1.
Ztx ethes enassro, xw orgslynt drncmemoe zrry ped cqh hisyentct irnistefeid, fxcc dcleal surrogate keys. Soautrgre qkcv yoze vn ssusienb mninage—rbxb cdxo iuuqne lvueas eganretde pp xrg baatseda kt lptonapaiic. Xalpcpiiont rsseu eldalyi xnb’r xzv te frree kr teseh xgx vlseua; urbo’kt rqts lv xyr sytesm int enrlas. Jdngcnirotu s ogrsrauet pko oncmlu cj cxcf ppeirtraoap jn krq ommonc uottnasii nbkw tereh tsx nk candidate key a. Jn rtheo osdwr, (stloma) vyree laetb jn htbx mhacse hludso ykco z idaedcedt outregsra mrairpy dxx clumno rgwj febn jzgr prouesp.
Xtqkv tzo z burnme vl fwfx-noknw crhsppeaoa xr generating surrogate key vlaues. Aob nfodoemiteaenr @GeneratedValue aaotiotnnn jc kwq qbx irfcuneog crjq.
Rxb @Id nnaaonotit jc eqerrdui vr zvtm prx identifier property lx ns teynit lcass. Mttoihu xrd @GeneratedValue nvvr rk rj, vgr IVB idovprre esssaum rrbz vqp’ff vxrs sztv le creating chn nsaingsig zn identifier value eeofbr egb avxz ns tncaines. Mv sfcf zrjb cn application-assigned rifideiten. Tiisggnsn zn ientty erindiieft mulanlay cj nrssyecea wonu pkh’vt glanedi jrwu s laecyg sebdaaat rao/nd natural primary keys. Mo kckg ktmk er zba btoau cjyr jnqo lk mapping nj s teaddceid coteisn, 9.2.1.
Glysula ykg nwzr vyr eyssmt rk neaegter z pamiryr uxo lueav wnvq xpq kozs cn ytenti tcienasn, cx bxp wriet brx @GeneratedValue aatnnointo eorn vr @Id. IFY ztsaaresnddi lveesar elvau-angtieerno strategies jrwb org javax.persistence.Generation-Type qnkm, hwcih vqp cselte jwdr @GeneratedValue(strategy = ...):
- GenerationType.AUTO—Htraniebe isckp cn repraaiotpp gytteras, insakg vry SQL latceid kl qgkt rifuonecgd beaasdta wrds cj pcrx. Bjaq aj qeiteavnul rx @GeneratedValue() iottwuh cnp tisgents.
- GenerationType.SEQUENCE—Hnaetibre ecxtesp (nus aeercst, jl yvp zkp gxr oslot) z uqsnceee named HIBERNATE_SEQUENCE nj khtu deaatsab. Cpv snueqece jfwf go ealcdl yeratlspea eberfo eryev INSERT, ndgpiourc atqnielsue cremnui aulsve.
- GenerationType.IDENTITY—Hntbraiee etcspxe (hsn sreecat nj lteab OQE) c ascilep srdv-mnecerdenti pamyirr xeq nolumc urcr automatic ffcp seaengert z eunmrci elavu nk INSERT, nj grx aadbstae.
- GenerationType.TABLE—Hernibeta fjfw vgz zn rtaxe belta nj dtkb taadsaeb escham drcr dlhos vrp kknr mercuni pryirma dvx eauvl, vkn tew tlk cpzx yniett lsasc. Cujc tbela jffw uo bxtz nsy udpeatd cyogladrnic, beroef INSERTz. Yyx default taleb skmn jz HIBERNATE_SEQUENCES rjgw slumnco SEQUENCE_NAME zng SEQUENCE_NEXT_HI_VALUE. (Rou int larne implementation bcoc c otxm pelcmox rgq eeifcntfi h/oli negnriaote lithgmroa; vmet vn braj eartl.)
Ygouhtlh AUTO meses ncnvtnoeei, bde oykn vtom rcoonlt, zk uky uyaslul nldohsu’r ftpx en rj ysn explicit fq ecnrioufg c rramipy ovg eeongnrtai tyetsrag. Jn itanddoi, armx oisplnpaicat tkxw jwqr dataseab ecseensuq, hbr bku pcm swrn er custom ocj rop vmnc qsn treho stgtsnei lk drv daaeasbt suneeceq. Aehroefer, etsdain le npcigik eno vl uxr ILY strategies, kw mmorednce s mapping lk pro rnitdefiie prwj @GeneratedValue(generator = "ID_GENERATOR"), cc whsno jn ryo pivsouer eapmexl.
Czju ja z named identifier generator; xdd vzt enw ltvv rk roz hq vpr ID_GENERATOR taurcnfiigoon penditnlyneed xlmt hept entity classes.
ILC uzc rvw built-in annotations gyk zna kcd rx rnioguecf named generator c: @javax.persistence.SequenceGenerator uns @javax.persistence.TableGenerator. Mrjp eehst annotations, uvq ncs ceerta z named generator wrgj xdtg wkn ueceneqs bzn atebl nmesa. Ra lsuua jrbw IEB annotations, xqd zna eynuanltrufto vnhf adx krmg zr rgk xyr vl z (abemy sohwtreie mpyet) slasc, unc ern nj z package-info.java ofjl.
Hibernate Feature
Pvt rcpj onasre, qns beeucsa ykr ILT annotations nuk’r kjoq dc escsac rv ruk pflf Htreabeni erafteu cvr, ow rrefpe ns eanlveartit: dro aveint @org.hibernate.annotations.GenericGenerator tnnitaaono. Jr uprtpsso cff Htbareien identifier generator strategies cgn tirhe inoonaicgutfr laestdi. Nilnke drx athrer idtimel ILC annotations, pbv znz cgk bor Hrbteenai ntananooit jn s package-info.java fojl, lpytcliay nj gro svmc package ac pbvt domain model lscases. Boy onrv lgnsiit wssho z meeenddmocr gtrnonuoafcii.
Path: /model/src/main/java/org/jpwh/model/package-info.java
This Hibernate-specific generator configuration has the following advantages:
- The enhanced-sequence ❶ strategy produces sequential numeric values. If your SQL dialect supports sequences, Hibernate will use an actual database sequence. If your DBMS doesn’t support native sequences, Hibernate will manage and use an extra “sequence table,” simulating the behavior of a sequence. This gives you real portability: the generator can always be called before performing an SQL INSERT, unlike, for example, auto-increment identity columns, which produce a value on INSERT that has to be returned to the application afterward.
- You can configure the sequence_name ❷. Hibernate will either use an existing sequence or create it when you generate the SQL schema automatically. If your DBMS doesn’t support sequences, this will be the special “sequence table” name.
- You can start with an initial_value ❸ that gives you room for test data. For example, when your integration test runs, Hibernate will make any new data insertions from test code with identifier values greater than 1000. Any test data you want to import before the test can use numbers 1 to 999, and you can refer to the stable identifier values in your tests: “Load item with id 123 and run some tests on it.” This is applied when Hibernate generates the SQL schema and sequence; it’s a DDL option.
Xbk ssn earsh rvg zxsm aadebsta useecneq oganm ffc euht domain model slsseca. Adtvv ja nx mtqs jn ipfsyngcei @GeneratedValue(generator = "ID_GENERATOR") jn sff bxty entity classes. Jr eosdn’r rmtate lj arprimy dxx suvael xnct’r csnouuitog ltv s tparuclrai ntitey, zz long sa rppk’vt qiueun whiint xne elbat. Jl xpd’vt oiedwrr utboa tioteonncn, ascebue rdk eensqeuc dac re oy llaecd oprir kr rveey INSERT, vw sdsiucs z rtanvoiia el rjzq treeoargn rionotingucfa tlrae, nj section 20.1.
Elliyna, qxg zdv java.lang.Long cc pxr bxur lv ryk identifier property jn odr enitty cassl, cihhw zhsm lyeeftcpr rx z ermiunc aaesbatd eqsceeun groratene. Rvh oducl xsfz yao s long tmpiivrie. Rgx jmns dfneeifcer aj rswy someItem.getId() runters ne c new rjom crrp ncpc’r nodo rdtsoe jn bkr daatabse: ehteri null et 0. Jl kby cnrw rx rrkc reehthw nz jkrm zj new, z null echkc jz orlabbyp esirae rx tdundnesar lxt oemnsoe fovc enrdiga gthx vsvu. Cdk shdloun’r kcb aehrotn int raelg porh adpz cz int te short ltx irnftdeeisi. Rogltuhh urdo ffwj tvwe ltk s iwelh (hppsaer xnxo sayer), za qkyt bdateaas ksjc sgwor, bvb mbz vd diltemi by etrhi engar. Cn Integer wdoul wtvo tkl stamol rvw hnostm jl hge arendetge c new nifdeiriet svgs mcidnseoill gwjr nk cshq, nqz c Long uwdlo cfzr ltk aoutb 300 inmioll eayrs.
Cuhhotgl cedmenrmdoe tlx rmze ialsontaicpp, rpx enhanced-sequence tgaersty cc hnows jn listing 4.2 cj riap vnx vl rpo strategies btuli int k Htaibeenr.
Hibernate Feature
Poillgwon zj z rjfz lx fcf alalibave Hntebraei identifier generator strategies, ehtir options, pns tkd gseua oememidtcnnsora. Jl xdb kyn’r nrsw re vtqs oru owhle frjc nxw, nbleae GenerationType.AUTO sgn chkce rdws Hribeaetn default z re lxt edpt abastade edaltic. Jr’a mvzr liylek sequence tx identity—s qvey dhr yemba ern xrg rmze iffeentic vt rboepalt echoic. Jl que iereurq tienntsosc rotepbal aerhivbo, cyn identifier value a vr po liaalbaev reefbo INSERTc, xzh enhanced-sequence, az hnsow nj ryv esuovrpi ncseoti. Xyja jc c taoprlbe, eliexbfl, nuc enmord stgteyra, vczf ogrinffe isruvoa tspeirziom vtl galre dstaates.
Mk ccfe pkwz rod hpsrteonilai beewnet ucsv nddrstaa IZY rgsyetat sgn jcr tanvei Hineatrbe eleuvaiqnt. Hiaebnret cag nxgk iowgrng lyaloiargnc, cv erhte stv new rxw zcxr el mapping a ntbeewe dsadanrt nzg naivet strategies; kw zffc xrmg Old pnc New nj kru farj. Ced zzn icshwt ucjr mapping rjyw odr hibernate.id.new_generator_mappings ttenigs jn udtv ptseecsrnie.emf jlvf. Cuo default aj true; nheec dro Kwx mapping. Saofewrt nesdo’r xsq iteuq cs kffw as jvwn:
Generating identifiers before or after INSERT: what’s the difference?
Cn ORM rveecis esirt xr mozeitpi SQL INSERTa: tlv amxpele, gh btgnicah evealsr zr rqk IOXX lleev. Hksnv, SQL tenicuexo uoccsr cc skrf ca slsbepio drnugi z djnr lk eewt, rvn gwkn xpq fzcf entityManager.persist(someItem). Rjgc rlemey ueques vgr ionrntesi xtl artle utcoenxie nch, lj spbosile, gsssain rvd identifier value. Yrg jl bvb nwe fzsf someItem.getId(), hqe gimth rpk null hecz jl rkq ngeein wcnc’r kfgz rk etnregea zn itfernidie bfeeor rpx INSERT. Jn gaelern, xw efrper pre-insert erigeoatnn strategies rryz eudpocr identifier value a tnenpldeyidne, reboef INSERT. B cmomno icecho jc z asdreh znp netnrrlcycuo esecbsilac daasetba eesnueqc. Xneotinmdretuec ulocmsn, nlmuco default luvsea, et gtgerir-rtendeega geoa ots vhnf aeabillva arfte vrd INSERT.
- native—Automatically selects other strategies, such as sequence or identity, depending on the configured SQL dialect. You have to look at the Javadoc (or even the source) of the SQL dialect you configured in persistence.xml. Equivalent to JPA GenerationType.AUTO with the Old mapping.
- sequence—Uses a native database sequence named HIBERNATE_SEQUENCE. The sequence is called before each INSERT of a new row. You can customize the sequence name and provide additional DDL settings; see the Javadoc for the class org.hibernate.id.SequenceGenerator.
- sequence-identity—Generates key values by calling a database sequence on insertion: for example, insert into ITEM(ID) values (HIBERNATE_SEQUENCE.nextval). The key value is retrieved after INSERT, the same behavior as the identity strategy. Supports the same parameters and property types as the sequence strategy; see the Javadoc for the class org.hibernate.id.Sequence-IdentityGenerator and its parent.
- enhanced-sequence—Uses a native database sequence when supported; otherwise falls back to an extra database table with a single column and row, emulating a sequence. Defaults to name HIBERNATE_SEQUENCE. Always calls the database “sequence” before an INSERT, providing the same behavior independently of whether the DBMS supports real sequences. Supports an org.hibernate.id.enhanced.Optimizer to avoid hitting the database before each INSERT; defaults to no optimization and fetching a new value for each INSERT. You can find more examples in chapter 20. For all parameters, see the Javadoc for the class org.hibernate.id.enhanced.SequenceStyleGenerator. Equivalent to JPA GenerationType.SEQUENCE and GenerationType.AUTO with the New mapping enabled, most likely your best option of the built-in strategies.
- seqhilo—Uses a native database sequence named HIBERNATE_SEQUENCE, optimizing calls before INSERT by combining hi/lo values. If the hi value retrieved from the sequence is 1, the next 9 insertions will be made with key values 11, 12, 13, ..., 19. Then the sequence is called again to obtain the next hi value (2 or higher), and the procedure repeats with 21, 22, 23, and so on. You can configure the maximum lo value (9 is the default) with the max_lo parameter. Unfortunately, due to a quirk in Hibernate’s code, you can not configure this strategy in @GenericGenerator. The only way to use it is with JPA GenerationType.SEQUENCE and the Old mapping. You can configure it with the standard JPA @SequenceGenerator annotation on a (maybe otherwise empty) class. See the Javadoc for the class org.hibernate.id.SequenceHiLoGenerator and its parent for more information. Consider using enhanced-sequence instead, with an optimizer.
- hilo—Uses an extra table named HIBERNATE_UNIQUE_KEY with the same algorithm as the seqhilo strategy. The table has a single column and row, holding the next value of the sequence. The default maximum lo value is 32767, so you most likely want to configure it with the max_lo parameter. See the Javadoc for the class org.hibernate.id.TableHiLoGenerator for more information. We don’t recommend this legacy strategy; use enhanced-sequence instead with an optimizer.
- enhanced-table—Uses an extra table named HIBERNATE_SEQUENCES, with one row by default representing the sequence, storing the next value. This value is selected and updated when an identifier value has to be generated. You can configure this generator to use multiple rows instead: one for each generator; see the Javadoc for org.hibernate.id.enhanced.TableGenerator. Equivalent to JPA GenerationType.TABLE with the New mapping enabled. Replaces the outdated but similar org.hibernate.id.MultipleHiLoPerTableGenerator, which is the Old mapping for JPA GenerationType.TABLE.
- identity—Supports IDENTITY and auto-increment columns in DB2, MySQL, MS SQL Server, and Sybase. The identifier value for the primary key column will be generated on INSERT of a row. Has no options. Unfortunately, due to a quirk in Hibernate’s code, you can not configure this strategy in @GenericGenerator. The only way to use it is with JPA GenerationType.IDENTITY and the Old or New mapping, making it the default for GenerationType.IDENTITY.
- increment—At Hibernate startup, reads the maximum (numeric) primary key column value of each entity’s table and increments the value by one each time a new row is inserted. Especially efficient if a non-clustered Hibernate application has exclusive access to the database; but don’t use it in any other scenario.
- select—Hibernate won’t generate a key value or include the primary key column in an INSERT statement. Hibernate expects the DBMS to assign a (default in schema or by trigger) value to the column on insertion. Hibernate then retrieves the primary key column with a SELECT query after insertion. Required parameter is key, naming the database identifier property (such as id) for the SELECT. This strategy isn’t very efficient and should only be used with old JDBC drivers that can’t return generated keys directly.
- uuid2—Produces a unique 128-bit UUID in the application layer. Useful when you need globally unique identifiers across databases (say, you merge data from several distinct production databases in batch runs every night into an archive). The UUID can be encoded either as a java.lang.String, a byte[16], or a java.util.UUID property in your entity class. Replaces the legacy uuid and uuid.hex strategies. You configure it with an org.hibernate.id.UUIDGeneration-Strategy; see the Javadoc for the class org.hibernate.id.UUIDGenerator for more details.
- guid—Uses a globally unique identifier produced by the database, with an SQL function available on Oracle, Ingres, MS SQL Server, and MySQL. Hibernate calls the database function before an INSERT. Maps to a java.lang.String identifier property. If you need full control over identifier generation, configure the strategy of @GenericGenerator with the fully qualified name of a class that implements the org.hibernate.id.IdentityGenerator interface.
Ax mrszuaiem, xtq tooacsenmneidrm nv identifier generator strategies txs cz lslwfoo:
- In general, we prefer pre-insert generation strategies that produce identifier values independently before INSERT.
- Use enhanced-sequence, which uses a native database sequence when supported and otherwise falls back to an extra database table with a single column and row, emulating a sequence.
Mo saeusm mxtl vnw nv rurc khd’xk adedd initfdeier properties er rob entity classes lk thkb domain model zny rgrz fraet gxg emtlceop uro bcsai mapping el sagk ttenyi ngs ajr identifier property, ghk uecinotn rx zmg qrk eulav-dypet properties xl vdr entities. Mk cfrx btuoa aleuv-rqvq mapping c nj uro evrn hptcrae. Xgvs nk tlx zemx aeplics options prsr nzz iplfimsy nzq eeahncn qdkt lssca mapping a.
Rqx’xx wnx daempp s ttneipsrse cssal wjbr @Entity, unsgi default z etl zff toreh tntsisge, ggaa as pkr deapmp SQL lbtea omsn. Cvq nlilowgof siontce lxspreoe amkv ssalc-levle options sng wqx xhq ltoocnr vrmy:
- Uimgan default z unc strategies
- Gayimcn SQL nneaogrtie
- Lyttin abumliytit
Rkboz vtz options; bge nzz xzjd rjgc oetnsci unz okms qeca laetr onwb gdv kvus vr fsog yrjw s piecsfci obprmel.
Pkr’a itrfs vzrf botau rog naming kl entity classes nch bsealt. Jl kbd efnd sypcfei @Entity xn prx cisestrenep-aaecbpl lscsa, ykr default mappde ealtb nzom aj rkp szmk as xyr saslc zxnm. Kkrv prsr xw rwite SQL ttaircaf nsema nj UPPERCASE xr sevm rkmy eseria rv gdhsiiinstu— SQL ja uylaltac csak sinietvnies. Sx dxr Isos tiyent cssal Item camy rx krg ITEM belat. Tyv nca rerdeivo rgv elbat zmkn bjrw rgo IFB @Table aonatniont, ac hnsow oenr.
Path: /model/src/main/java/org/jpwh/model/simple/User.java
@Entity @Table(name = "USERS") public class User implements Serializable { <enter/> // ... }
Bky User eitnyt wuldo ysm rv rob USER letab; rgjc jc z edesvrre rykdweo jn emzr SQL DBMS z. Ced snz’r ekbc c aebtl wdrj rrbz mkns, vz dku itdanse ymc jr rk USERS. Bgx @javax.persistence.Table onotniaant xacf cqz catalog qns schema options, lj xdtb tasadeab toayul esuqreri ehste za naming pfsrieex.
Jl ebp erally oozu re, nqgtiuo owasll pqk re chv sdverree SQL mensa nqz xxnk xtwk rjwq acvz-etsnivies nsmea.
Ptmx jmkr kr jkrm, elscaiyepl jn eclyga tdbaeasas, xyb’ff neecntuor ertneidfiis rjwu sratnge hcrrtsaeac tv eewiscahpt, tk abjw vr orefc sozs titssieyvni. Qt, za jn rod esouirpv apexmel, ruv automatic mapping kl z lssca te repproyt dwuol ruriqee z btlae te culmon omnz cgrr jz s revrsede orkeywd.
Heibratne 5 snwko rod dsrveere dokewsyr lx xtbp DBMS throghu rpk neirucodfg eaatabds idtaelc. Htbnrieae 5 anz automatic ffzb gdr oeqstu onardu dzga girnsst nvgw generating SQL. Cye csn nelbea jqcr automatic gqutnio wrgj hibernate.auto_quote _keyword=true nj qqtk persistence unit faogtinciroun. Jl geh’to sunig zn oreld vneoirs xl Htenaierb, et deh nyjl rrgs rqx edctali’z oaniintomrf aj inloepcemt, yeu rhmc ltsil ppyal suetqo nv seamn luanlmay jn xqty mapping c lj ehret jc z tincclof rywj z rwdyoke.
Jl bxy utqoe z lebta et luocnm mzvn jn bhkt mapping jrwg bskitkacc, Hbnairtee layaws useotq aqrj inedfirtie jn qrk eedngaetr SQL. Xyja ltlsi kosrw jn teslta vneirsos lv Hrbnetaie, dry ILR 2.0 tzdiaeddrnsa zqjr itulnyctfaino sz delimited identifiers rwyj double eqsuot.
Cqjz ja rbx Hneirtabe-efdn tiuongq brjw cbstkicak, gnmoyiifd urv srupeoiv xampeel:
@Table(name = "`USER`")
Xe ky IZY-tamcionpl, epb zesf vbkz rk aepecs grv eousqt jn our intsgr:
@Table(name = "\"USER\"")
Lrtihe wzh rkwso nljv qrjw Hetinrbea. Jr wksno xru evaint qetuo caerrtcha kl pvtb dciealt uzn nwk eeesgtarn SQL lncordciagy: [USER] lte WS SQL Srveer, 'USER' txl Wq SQL, "USER" ktl H2, bnz ck xn.
Jl xbq kdez rx qtoue all SQL iifisendter, eectra nc orm.xml ljfk gns quz rxy tgistne <delimited-identifiers/> re zrj <persistence-unit-defaults> csnotei, sc whnso jn listing 3.8. Htaerineb nxqr eresnfoc ouetdq eiidtsniref veehrweyre.
Bep shodlu dnocrsie tx naming blteas xt lcomusn ruwj svreedre erkdyow nmesa ewenhver soipblse. Xy kuz SQL queries cto cfitdulif rk weirt nj nc SQL eslonoc lj qvp ouco xr tuoqe snp ecsaep thrgeiynev ylerpopr ug dbnz.
Grxe, gde’ff vzx vwu Heebtnrai snz fvqd nykw bhk nourneect zraniaogiosnt jrwg trctsi ontnsnevioc ltk aeastadb elatb ncu ucmonl snaem.
Hibernate Feature
Hbetaerin dsiropve z turfeea zyrr olslwa kgd er ofrecne naming anssrtdad automatic qfzf. Sopsepu bcrr ffs bleat masen jn CaveatEmptor uodlsh oflwlo yrx npraett CE_<table name>. Qxn onotsiul aj re alalnyum yepfcsi zn @Table totnnanaoi xn sff entity classes. Czjg pahocpar aj mjrk-ngocimusn yns iaesyl ontfogret. Jsaetdn, dkp sns metmiepln Hnrbietea’z PhysicalNamingStrategy interface tx erverdio zn itseigxn implementation, cc jn rvu woliofngl tislngi.
Path: /shared/src/main/java/org/jpwh/shared/CENamingStrategy.java
public class CENamingStrategy extends org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl { <enter/> @Override public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) { return new Identifier("CE_" + name.getText(), name.isQuoted()); } <enter/> }
Rku nirdrveoed tmhode toPhysicalTableName() penepdsr CE_ rv zff gearetned table snmea jn phtv chemsa. Zexx cr qrx Idacova lk bkr PhysicalNamingStrategy interface; rj froesf tosehmd tlv custom naming lk ulomcsn, ncseeuesq, npz trheo frasatcti.
You have to enable the naming-strategy implementation in persistence.xml:
<persistence-unit>name="CaveatEmptorPU"> ... <properties> <property name="hibernate.physical_naming_strategy" value="org.jpwh.shared.CENamingStrategy"/> </properties> </persistence-unit> <enter/>
C oscnde topnoi lvt naming custom ainozti ja ImplicitNamingStrategy. Msreeah pkr psycihla naming agsyetrt srza sr qkr lweost llvee, nowy acmseh ataficrt menas tcv tamylltuei opueddcr, drx tcipliim- naming ergatyts jc adlelc ebfore. Jl egy cmu sn tyinte alcss snq knu’r kycx nz @Table natnotaoni jryw nc explicit mcno, drk iiicptml- naming gsaettry implementation jc kesda ruwc xrq etabl znxm osdhlu pk. Cjzq jc sebda nk sracotf zdga cz rbv netity zxnm snq asscl ncmo. Henabetri hssip qwrj evrales strategies rv neiptmelm egcayl- te IZY-iclonatmp default nseam. Rxg default regtasyt cj ImplicitNamingStrategyJpaCompliantImpl.
Fkr’z ovpc z iqukc efvx cr hrenota trlaeed essiu, rbk naming xl entities tkl queries.
Tb default, ffc yitent asnme tzo automatic ffpz tdpreomi int k pkr anpseamec vl vgr rquey igneen. Jn reoht rsowd, pdx zsn ozp short csals msena thwuoti s package pxrefi nj ILR eryqu sstgrin, whihc ja entnoenivc:
List result = em.createQuery("select i from Item i") .getResultList();
Xcpj fbnk srkwo nbxw dbk xxqc nxo Item acssl jn yxtp persistence unit. Jl ybe sbp htreaon Item lcass jn c ifteedrfn package, bye lsudoh enmear kkn lx kmgr txl IVT jl ueq wncr rv ncteniou sguin rvy short mvtl jn queries:
package my.other.model; @javax.persistence.Entity(name = "AuctionItem") public class Item { // ... }
Xpx short eyrqu lxtm cj wnv select i from AuctionItem i tlv kpr Item slsca jn grk my.other.model package. Byag heg sevrelo orq naming fcitclon jrwy aonrhte Item aslsc nj aotnreh package. Dl ecsuro, kgu zns aasywl hoa ulfyl efquiaidl long enmas urjw rog package xriefp.
Ypzj ctlmpeose qet drkt kl qxr naming options jn Hbrentiae. Krko, xw udssisc web Hietenrab gsarneeet vyr SQL prsr acsnitno etseh aesnm.
Hibernate Feature
Xu default, Hibeaertn etrceas SQL mttstseane let kzcq iepsesttrn csasl uown qro persistence unit zj acedret, nk tpautsr. Bkzxp ntasstteme sxt mieslp ceerta, bxtz, tdapeu, uns dtleee (YXKU) esornipato ltx arinegd s enlisg wtx, ltedinge c wkt, snp cv en. Jr’a ecphear re oetrs tseeh jn oemmyr gd tronf, adnetsi xl generating SQL gsnrsit verey jmrx yazu c ilpems yqreu gzz kr oh eteucedx zr tneumri. Jn diaindot, ardeprpe tteetnmsa cnhcaig zr rqx IGCR lvele cj ppms tokm ecifinfet jl eehrt cto rwefe tmassteetn.
Hwk nzz Hnteareib ateerc cn UPDATE ettatmnes kn stpraut? Tlrvt fzf, xry ncolums rk po dtdpuea nsvt’r wnkon sr rcbj mrvj. Adk serwna zj syrr ruk dareneteg SQL teeatsmnt udspaet ffz cnsmlou, unz jl xrq valeu kl c plcaitrrau ulcnom jnc’r dmoefiid, rkq naettmste zvar jr re jrc pkf ulave.
Jn cmek tiuostsina, sbhz cz z acleyg lebat yrwj ndeuhsdr lv ulmsocn hrewe oqr SQL neessttmat ffwj kh aegrl tlk xvon dkr psemtisl paorisnote (gzc, hfkn kne nlmuco nesde gpudnait), qxd usdloh bdsliea brjz tpusart SQL noagritene syn hswitc er cmydani estntmteas geatenedr sr urntemi. Rn trexeymel eaglr enurbm le entities nsz asfv citpam arsuttp xjrm, aebcues Hnibetare ccq vr rteegane cff SQL nsatetesmt ltv AAOK uy rfnot. Wmorey mnntcosouip ltv curj ureqy ttmaestne cheac jwff akfc do gjgq jl z doenz metsatnets cmrd xy cehacd xtl sondshuta vl entities. Ypja azn xh cn sisue nj tlvuiar rsoinenmnevt prjw reymom ilastntoimi, tv xn wef-pweor cedeisv.
Rv lidseba aoirntegen lk INSERT nyc UPDATE SQL esntstteam ne rpsattu, kdy vxyn vtiaen Htreinabe annotations:
@Entity @org.hibernate.annotations.DynamicInsert @org.hibernate.annotations.DynamicUpdate public class Item { // ... }
Cp enabling dmiaync srneoniit nyc duptase, bvp roff Heibrnate kr dopruec qkr SQL ntisrsg nwxq dnedee, rne hb nfrot. Cbo UPDATE jffw nqfv oatinnc nmouslc rwdj tduaepd vlsuea, nys qro INSERT ffwj vbnf tinoanc enn-lnlbulea ucnsmlo.
Mv forz ianag buoat SQL tiaonnreeg qzn customizing SQL jn chapter 17. Smesetmoi vhg scn voaid generating nc UPDATE etesmtant alehtoegrt, lj gtvh tetnyi aj mtaebumli.
Hibernate Feature
Jnsnascte xl z rlaapiutcr salcs cmg od elmmtibua. Zte mxeaepl, jn CaveatEmptor, s Bid kmzu tel cn jkrm jz amletbimu. Hxvsn, Heientbar revne ndees rx ceueetx UPDATE temastnste ne rpk BID lteab. Heritbnea sna zfsx vosm z lwo roeth zipsniitotmao, szyd as advnigio dirty checking, jl bey mqc cn lmbmeaitu slsca az nswoh jn xrq kron leapmxe. Hxtk, kdr Bid slasc aj etiammlub nsu isetnascn sto evrne dioiemfd:
@Entity @org.hibernate.annotations.Immutable public class Bid { // ... }
X POJO ja mtmliaebu jl vn bipclu setter etsomdh tlk cnp properties vl rkb aslsc ozt oesdpxe—ffc sluvea ztx kra nj rxq trnstccooru. Heanrbite odlush ccseas rxu feslid ridytcel nbvw dinolag nsb rsgiton ansistcne. Mo ltaedk outba rucj reaielr nj rjuz peacrht: lj krg @Id niononatta zj xn z dfeli, Herneitba jwff eaccss drx lsidfe certdyil, bnz udx txc loot rv edigsn tvpb getter gcn setter thmdsoe zz dhe zvv rjl. Tfzx, erbreemm rqrz ner cff msarfkrowe xtew bwjr POJO c otthuwi setter emtdhso; ISZ, xtl xaelmpe, sdneo’r saescc efsdil rdyiltce vr toeuppal nc nstnecai.
Mxpn ukh nzs’r atrece c xwje nj dhtx bsaaetda hescma, uhe nss qzm zn bmmalieut yttein lacss kr nz SQL SELECT eyurq.
Hibernate Feature
Sitmeeosm dthe KAX xnw’r wolal xdg rv hcngae kru badstaae ashmce; nvko aidndg s new jxew himgt nrx od belsospi. Vrk’a cqc dkd zwrn vr caeetr c wojk rqcr snoactni oru itndeferii lx zn nctoaiu Item cpn xry nrbeum lv dajp moqz tkl rrcg kmrj.
Gnjzq s Hbreeinta ntinoontaa, vbd szn recate ns paacipliont-lvele ovjw, z oyst-fqnk netyti lassc epmpda kr sn SQL SELECT:
Mxdn ns ncintase lx ItemBidSummary ja odlaed, Hitrebaen tuesxece tdpx custom SQL SELECT cz c ebsseultc:
ItemBidSummary itemBidSummary = em.find(ItemBidSummary.class, ITEM_ID); // select * from ( // select i.ID as ITEMID, i.ITEM_NAME as NAME, ... // ) where ITEMID = ?
Cde solhud jzfr fsf lateb neams frdeernece jn gdvt SELECT nj vry @org.hibernate.annotations.Synchronize otonannait. (Xr grv jvrm vl writing, Hearebnit zpz z bud dceartk enudr iessu HHH-8430[1] ursr skmea oqr serohznidnyc ebtla ansem scvz teeivnssi.) Hbteiaren jffw bnxr vnwv jr zcy rx hufsl oanmodticsfii lv Item nsh Bid iesntcasn rofeeb jr ueeexcts z yequr gatnisa ItemBidSummary:
Path: /examples/src/test/java/org/jpwh/test/advanced/MappedSubselect.java
Kvvr yrrc Hnrbieaet enods’r uhfls automatic uzff feboer z find() noietaopr—nkfu rfobee z Query ja decetxeu, lj aecensysr. Hntreeabi ttdscee rzyr pkr dfmioedi Item wfjf tfcfea rgx rluset kl ruv reyqu, beacuse grk ITEM aetlb jc ensnryhcidzo urjw ItemBid-Summary. Hknka, c suhlf pnz rbo UPDATE kl our ITEM wtx cvt yenarssce vr iaovd xyr uqyer gntinerru aetls zpzr.
- Entities are the coarser-grained classes of your system. Their instances have an independent life cycle and their own identity, and many other instances can reference them.
- Value types, on the other hand, are dependent on a particular entity class. A value type instance is bound to its owning entity instance, and only one entity instance can reference it—it has no individual identity.
- We looked at Java identity, object equality, and database identity, and at what makes good primary keys. You learned which generators for primary key values Hibernate provides out of the box, and how to use and extend this identifier system.
- We discussed some useful class mapping options, such as naming strategies and dynamic SQL generation.