Вы находитесь на странице: 1из 29

Persistence framework

Persistence Framework

Objectives

Understanding Database Encapsulation Advantages and Disadvantages of Database Encapsulation Implementation Strategies Persistence Framework JPA API Best Practices

2
Persistence Framework

Encapsulation
!e term encapsulation is often used interc!angeabl" wit! information !iding# it is t!e !iding of design decisions in a computer program t!at are most likel" to c!ange# t!us protecting ot!er parts of t!e program from c!ange if t!e design decision is c!anged$ !e protection involves providing a stable interface$ In modern programming languages# t!e principle of information !iding manifests itself in a number of wa"s# including encapsulation %given t!e separation of concerns& and pol"morp!ism$
Persistence Framework

Encapsulation on Database
!e implication of encapsulation is t!at we can build components and c!ange it later wit!out affect ot!er components wit!in t!e s"stem as long as t!e interface to t!at component did not c!ange$ Database is t!e place for information storage# we can also !ave various encapsulation arc!itectures# and implementation strategies so t!at we can decouple t!e code wit! t!e database s"stem including t!eir p!"sical sc!emas from business code $ a t"pical arc!itectural la"ering strateg" for building business applications w!ic! includes a database encapsulation la"er %also known as a persistence la"er or simpl" a data la"er&$

Persistence Framework

A Brief History of Persistence Starting from '(((# developers figured out# t!at accessing relational databases using )ust*directl" JDB+ is a rat!er dirt"*ugl" wa"$ !e differences in ob)ect,oriented design and relational databases got too obvious$ a number of pro)ects including opensource !ave been set up to solve t!is problem in a more elegant wa" -ibernate# +astor# +a"enne# .JB# or/ue# D.DS# oplink# iBatis# AD. and etc ob)ect,oriented databases were at t!at time alread" more or less p!ased out$
Persistence Framework

Database Encapsulation Befits


It reduces t!e coupling of ob)ect and database so t!at increasing abilit" to evolve eit!er one$ It implements all data,related code in one place$ It make t!e programmers )ob easier$ It gives "ou a common place to implement data,oriented business rules$ It allow to takes advantage of specific database features# increasing application performance It allows application programmers to focus on t!e business problem and DBA%s& can focus on t!e database$ %separation of responsibilities&

Persistence Framework

Database encapsulation disadvantages


!ere are potentiall" several disadvantages of database encapsulation0 Increase t!e Investment$ !e" often re/uire reasonabl" clean 1apping$ Provide not enoug! control over database access$

Persistence Framework

Implementation Strategies For Database Encapsulation Layers


Just 2uer"0 business ob)ects access data sources directl" b" submitting Structure 2uer" 3anguage %S23& or .b)ect 2uer" 3anguage %.23& code to t!e database Data access ob)ects%DA.&# it encapsulate t!e database access logic re/uired of business ob)ects# It also !ave industr",standard approac!es suc! as Java Data .b)ect %JD.& and Active4 Data .b)ect %AD.&$

Persistence Framework

Implementation Strategies For Database Encapsulation Layers


Persistence framework*tools0 It encapsulates database access from business ob)ects$ Instead of writing code to implement t!e Database access logic # it re/uire to define meta data t!at represents t!e mappings$ Data Service0 It is an operation offered b" a component entit" or application t!at can be invoked b" ot!er entities# for e5ample$
> > > > > >

+ommon .b)ect 6e/uest Broker Arc!itecture %+.6BA& +ustomer Information +ontrol S"stem %+I+S& ransaction Distributed +omponent .b)ect 1odel %D+.1& Electronic data interc!ange %EDI& Stored procedures 7eb Services

Persistence Framework

W at is t e issue!
Some applications ma" not take advantage of t!e encapsulation la"er%s& and some ma" not# t!e" !ave to access data directl" to t!e Database $ legac" applications cannot access*not allow to t!e database encapsulation $ rework some of "our legac" applications to use t!e database encapsulation la"er cannot or will not performed*wanted$ !ere are some tec!nologies# suc! as a bulk load facilit" or a reporting framework# t!at re/uire direct access to t!e database sc!ema$
Persistence Framework

Note
!ere are still !ave values to implement database encapsulation because we can reduce coupling of ob)ect and DB and t!erefore reducing development costs and maintenance effort$

Persistence Framework

General Persistence Framework features


, 7rite S23 automaticall" , +reate Joins for -as, one 6elations!ips , Aggregate Sub/ueries , Support Paging , Allow for 8ersioning , +ascading operation

, -andle +olumn Aliases , Support In!eritance , 8alue .b)ects support , +ac!ing mec!anism

Persistence Framework

"ava Persistence #e$uirements


Simplification of t!e persistence model
> Elimination of deplo"ment descriptor

3ig!t,weig!t persistence model


> In terms of programming and deplo"ment model as

well as runtime performance

estabilit" outside of t!e containers


> +reate test clients t!at would use entities in a non,

managed environment

Domain modelling t!roug! in!eritance and pol"morp!ism .b)ect*6elational %.*6& mapping E5tensive /uer"ing capabilities
Persistence Framework

J PA Prim a r y Fe at ure s

P.J.,based persistence model

Plain .ld Java .b)ects In!eritance# pol"morp!ism# encapsulation# etc$ Java Persistence 2uer" 3anguage Using Java SE 9 Annotations and*or 413 oplink# -ibernate# :odo# .penJPA# Eclipse3ink

Supports traditional .,. modelling concepts

Standard abstract relational /uer" language

Standard .*6 mapping metadata

Portabilit" across providers %implementations&

Persistence Framework

Java Persistence P! "JP #


Java Persistence API %JPA& provides P.J. %Plain .ld Java .b)ect& standard and ob)ect relational mapping %.6 mapping& for data persistence among applications$ Persistence# w!ic! deals wit! storing and retrieving of application data# can now be programmed wit! Java Persistence API starting from EJB ;$( as a result of JS6 ''($ Java Persistence API !as borrowed man" of t!e concepts and standards from leading persistence frameworks like oplink %from .racle& and -ibernate %from JBoss&$ .ne of t!e great benefits of JPA is t!at it is an independent API and can nicel" integrate wit! J'EE as well as J'SE applications$

Persistence Framework

Principles on ow to use "P%


!e JPA is a specification# JPA provider implementations !ave to keep t!e Portabilit"$ Even for t!e provider,specific functionalit"# t!e" s!ould be easil" to identif" and isolated$ JPA,based code s!ould usuall" work in bot! Java SE and Java EE environment$ JPA code s!ould be portable across different datasources$ If database, specific features must be used# t!e" s!ould be isolated in configuration files rat!er t!an tainting t!e code$
Persistence Framework

Principles on ow to use "P%

Self,e5planator" code and annotations are preferable to comments t!at are necessar" to e5plain convoluted code$ !e best practices generall" re/uire ver" little e5tra effort to implement and provide long,term maintenance benefits at little or no cost in initial development time Service Provider Interface %SPI& for container*persistence provider plugabilit"$

Persistence Framework

"ava Persistence %PI &est Practices


Standard SQL for Database if required Effectively Use Database-Specific Features Select a suitable Layer for PA !ode Layer Favor Self-Describin" !ode over #etadata and !o$$ents Define %a$in" !onventions to &ave a #ore-'eadable !ode !onsider usin" Sprin" fra$e(or) to PA
Persistence Framework

"ava Persistence %PI &est Practices


!arefully !onsider and Select a #etadata !onfi"uration Strate"y Favor !onventions over E*ceptions Access Fields 'at&er +&an Properties ,#ore freedo$ Favor .E$bedded/d for !o$posite 0eys Use 1nly E*act Datatypes for Pri$ary 0eys,usin" inte"er Usin" Standard PA !ode Effectively Use /$ple$entation-Specific Features
Persistence Framework

Java Persistence P! Best Practices

6eplacing an eager loading strateg" wit! a la<" strateg" for related ob)ects# 3oading large static tables using JDB+ rat!er t!an t!e proprietar" persistence framework$ +ac!ing t!e results of /uer",intensive tables Using DB sort capabilities

Persistence Framework

Fut ure s
JPA 2.0. The focus is on refining, fixing, and improving portability. Some possible ne features of JPA 2.0!

"etter validation support, e.g. #$ength%&', #(ax%2' )mproved JP*$ support +riteria AP) support

Toplin, and -iberate already have this.

The -ash(ap li,e hints %e.g. logging, caching' to be standardised

toplin,.logging.level toplin,.cache.type.default

Persistence Framework

JP $%& proposed features

1ore fle5ible modeling Embeddable class support , embed a class into anot!er class wit!out mapping t!at class directl" to a table$ Instead it=s stored >embedded> inside anot!er class as a column in t!e table$ .rdered 3ists ? !e ordering applied to a /uer" to be persisted in t!e database$ From t!e database perspective# !ardwiring ordering in t!e database is done b" defining an inde5 column$ Access "pe , t!e process of defining w!et!er t!e provider uses fields or properties to access t!e elements of a class$ +urrentl" a single access t"pe applies to complete entit" !ierarc!"$ !e proposed c!ange is to allow "ou to specif" t!is on a per,class basis# @Access "pe%P6.PE6 A&annotation on an entit" class$

Persistence Framework

JP $%& proposed features


E5panded .*6 1appping Functionalit" Unidrectional one,to,man" relations!ips using foreign ke" Aou reall" don=t want bot! ends of one,to,man" relations!ip to !ave to know about eac! ot!er$ oda" "ou !ave to use a )oin table$ !is c!ange would allow "ou to specif" t!e relations!ip on one side onl"$

Persistence Framework

JP $%& proposed features

2ueries

Some current limitations0 SE3E+ clause too constrained$ .nl" supports aggregate functions Some unnecessar" restrictions on parameter usage , w!at about collectionsB 2ueries are alwa"s pol"morp!ic D"namic /ueries currentl" entail string construction$ !is is burdensome on t!e appaction to build t!is$ +riteria APIs allow >node,wise> /uer" construction$
+riteria2uer" c/ C em$create+riteria2uer"%+ustomer$class& $add%6estrictions$e/%>status># >preferred>& $add%6estrictions$e/%><ip># >D('E(>&F

!ere are alread" e5isting criteria APIs and e5pression language APIs available , -ibernate# .JB# +a"enne# op3ink# etc$

Persistence Framework

JP $%& proposed features

Standardi<ed !ints and properties

+urrentl" configuration properties and !ints are non, standard and specific to eac! provider$ 1an" could be standardi<ed# suc! as standard JDB+ properties# connection pool properties# cac!ing# cac!e si<e# logging# DD3 !andling# etc$ !e main issue wit! detac!ed ob)ects t!at t!e" !as to do wit! unfetc!ed state and relations!ips$ Detac!ed ob)ects often !ave unfetc!ed relations!ips$ At point of detac!ment# t!e state t!at=s available is determined b" t!e fetc! elements %b" default eager&# la<" fetc!ing for G o1an"H relations!ips$ !e E$( spec does not sa" w!at !appens w!en "ou do access unfetc!ed state$ JPA '$( be working on fi5ing Issue$

-andling detac!ed ob)ects

Persistence Framework

JP $%& proposed features

E5tended persistence conte5t

Allow entities to remain managed across multiple serial transactions$ Application,managed is alwa"s e5tended$ It is up to t!e developer to manage t!e lifec"cle of t!e persistence conte5t$ It is also up to t!e application to manage t!e association between a J A transaction and persistence conte5t$ .ne wa" to solve t!e issue is made t!e Entit"1anager detects it is in a transaction and registers wit! J A for notifications$ But t!e Entit"1anager is not alwa"s created at t!e beginning of a transaction# or "ou ma" !ave multiple active transactions# so t!e ot!er wa" to do t!is is to register t!e Entit"1anager wit! a transaction using em$)oin ransaction%&$ +ontainer,managed transactions is for Java EE environments# and provides a muc! easier solution$ !ere is an open issue wit! conversational state# passivation and clustering$ Basicall" it is not well defined w!at !appens w!en conversational state contains an Entit"1anager and gets passivated and reconstituted# particularl" on anot!er instance of a cluster$ JPA '$( will tr" to fi5 t!is$

Persistence Framework

JP $%& proposed features


8alidation JS6 ;(; on Bean 8alidation defines a metadata model and API for validation# for general use in SE and EE$ !e" want to leverage t!is in JPA but it depends on timing$ Some e5ample validations include @6e/uired# @3engt!%ma5C9& @1a5%'I(&# etc$ !e" are also looking at supporting user,defined validation# e$g$ @Ade/uatel"+ompensated$ 7!en "ou define t!ese validation annotations# t!e provider can automaticall" c!eck t!at t!ese constraints are met$

Persistence Framework

J'( )*+ and (!

JS6 ;EJ0 Java 1 Persistence '$( is now in Proposed Final Draft

!ttp0**www$)cp$org*en*)sr*detailBidC;EJ

Eclipse Persistence Services Pro)ect %Eclipse3ink& is going to be t!e reference implementation of JPA '$($

!ttp0**www$eclipse$org*eclipselink*

Persistence Framework

#esources
Klassfis! persistence !omepage !ttps0**glassfis!$dev$)ava$net*)avaee9*persistence Persistence support page !ttps0**glassfis!$dev$)ava$net*)avaee9*persistence*e ntit"persistence,support$!tml Blog on using persistence in 7eb applications !ttp0**weblogs$)ava$net*blog*ssEIE'E;*arc!ive*'((9 *E'*usingL)avaLpers$!tml Blog on sc!ema generation !ttp0**blogs$sun$com*roller*page*)ava'dbInKlassFis! MautomaticLtableLgenerationLfeatureLin

Persistence Framework

Вам также может понравиться