Chapitre 5 : JPA and EclipseLink Note • CecourscouvrelesbesoinslesplusimportantspourlapersistanceEn Java(vouspourrezretrouveruncourstrèscompletsurJPA2etsurla persistanceenjavaengénéralsurinternet). • UnebonneréférenceenlignesurJPA2 • http://www.objectdb.com/api/java/jpa,enparticulierlasectionJPA2 annotations Lapersistanceparsérialisation • Sérialisation=sauvegardedel'étatd'unobjetsousformed'octets. • Apartird'unétatsérialisé,onpeutreconstruirel'objet • Enjava,autraversdel'interfacejava.io.Serializable, desméthodesde java.io.ObjectInputStream etjava.io.ObjectOutputStream Lapersistanceparsérialisation • Défautstrèsnombreux… • Gestiondesversions,maintenance… • Pasderequêtescomplexes… • Ex:onsérializemillecomptesbancaires.Commentretrouverceuxquiontun soldenégatif? • Solution:stockerlesobjetsdansunebasededonnée! Ils’agitde:Object-Relational Mapping(ORM) • Theprocess ofmapping Javaobjects todatabase tablesandviceversa is called "Object-relational mapping"(ORM). • TheJavaPersistence API(JPA)is onepossibleapproach toORM. • JPAis aspecification andseveral implementations areavailable. • Popular implementations areHibernate,EclipseLink andApache OpenJPA. • Thereference implementation ofJPAis EclipseLink ! Principe:Object-Relational Mapping(ORM) • Onstockel'étatd'unobjetdansunebasededonnée. • Ex:laclassePersonnepossèdedeuxattributsnom etprenom,onassocie cetteclasseàunetable quipossèdedeuxcolonnes:nom etprenom. • Ondécomposechaqueobjetenunesuitedevariablesdonton stockeralavaleurdansuneouplusieurstables. • Permetdesrequêtescomplexes. Exemple(comptebancaire):Object-Relational Mapping(ORM) Qu'est-cequ'unEntityBean • Cesontdesobjetsquisaventsemapper dansunebasededonnée. • Ilsutilisentunmécanismedepersistance • Ilsserventàreprésentersousformed'objetsdesdonnéessituées dansunebasededonnée • Leplussouventunobjet=uneouplusieursligne(s)dansuneouplusieurs table(s) Qu'est-cequ'unEntityBean • Allentityclassesmustdefineaprimarykey,musthaveanon-arg constructorandornotallowedtobefinal.Keyscanbeasinglefield oracombinationoffields. • JPAallowstoauto-generatetheprimarykeyinthedatabasevia the @GeneratedValue annotation. • Bydefault,thetablenamecorrespondstotheclassname.Youcan changethiswiththeadditiontotheannotation @Table(name="NEWTABLENAME"). Exempleavecuncomptebancaire Atraversuneentité« Compte_bancaire » • Onlitlesinformationsd'uncomptebancaireenmémoire,dansune instanced'uneentitybean, • Onmanipulecesdonnées,onlesmodifieenchangeantlesvaleurs desattributsd'instance, • Lesdonnéesserontmisesàjourdanslabasededonnées automatiquement! Persistancedeschamps • By default each field is mapped to a column with the name of the field. You can change the default name via @Column (name="newColumnName"). • The following annotations can be used. Table 1.Annotationsforfields/getter andsetter @Id Identifies theunique IDofthedatabase entry @GeneratedValue Together with an ID this annotation defines that this value is generated automatically. @Transient Field will not be saved in database MappingRelationnel • JPAallows todefine relationships between classes,e.g.it can be defined that aclassis partofanother class(containment). • Classescan haveonetoone,onetomany,many toone,andmany tomany relationships with other classes. • Arelationship can be bidirectional orunidirectional,e.g. • inabidirectional relationship both classesstoreareference toeach other while inanunidirectional caseonly oneclasshasareference totheother class.Within abidirectional relationship you need tospecify theowning side ofthis relationship intheother classwith theattribute "mappedBy",e.g. @ManyToMany(mappedBy="attributeOfTheOwningClass". MappingRelationnel Relationshipannotations: • @OneToOne • @OneToMany • @ManyToOne • @ManyToMany Persistence units • Thepersistence unitis described viathe persistence.xml filein the META-INF directoryofthesourcefolder. • Asetofentities which arelogical connected will be grouped viaa persistence unit. • The persistence.xml filedefines theconnection datatothedatabase, e.g.thedriver,theuserandthepassword. Entity Manager • The EntityManager iscreatedbythe EntityManagerFactory whichis configuredbythepersistenceunit. • Theentity manager javax.persistence.EntityManager provides the operations from andtothedatabase,e.g.find objects,persists them, remove objects from thedatabase,etc. • InaJavaEE applicationtheentity manageris automatically inserted inthe webapplication.Outside JavaEE you need tomanagetheentity manager yourself. • Entities which aremanaged byanEntity Managerwill automatically propagate these changestothedatabase (ifthis happens within acommit statement). • IftheEntity Manageris closed (viaclose())then themanaged entities are inadetached state.Ifsynchronize them again with thedatabase aEntity Managerprovides themerge()method.