SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Downloaden Sie, um offline zu lesen
Introduction à JPA
(Java Persistence API )
Fouomene Pewo Daniel Rene
www.facebook.com/pages/FreelancerTech/822357474482862
www.twitter.com/FREELANCERTECH (@FREELANCERTECH)
Une équipe d’experts dans leur domaine technologique qui ont
décidé de se mettre ensemble pour offrir leurs services en
fonction de leurs disponibilités,
www.freelancertech.net
• Historique
• ORM : Object Relational Mapping
• JPA : Java Persistence Api
• Entity: Entités
• Autres annotations
• Contexte de persistance
• Opérations prises en charge par le gestionnaire d’entités
• Cycle de vie d’une instance d’entité
• Obtention d’une fabrique EntityManagerFactory
• Création du gestionnaire d’entité EntityManager
• Exemple d’insertion d’un livre
• Relations entre entités
• Référence
• Questions
Plan
www.freelancertech.net
Base de
donnée
MySQL
Couche
DAO
Couche
Métier
Couche
UI
JDBC
Historique : Accès directement à la base de donnée grâce à l’API standard JDBC de Java
• Pour des raisons de performances, le coût d'ouverture /
fermeture d'une connexion n'est pas négligeable,
o Connection con = DriverManager.getConnection(url, "login", "password");
o //les ordres SQL
o con.close();
• L’utilisation du langage SQL rend la couche DAO difficilement
maintenable,
o String insertStatement = "Insert into Client(Nom, Prenom,Nature) values (?, ?, ?)"
Problématiques de l’accès direct à la BD
à l’aide de jdbc :
www.freelancertech.net
Pour pallier à cette problématique et faciliter l’écriture de la couche
DAO,
La communauté Java a donc fait naître des Frameworks ORM ,
tels que Hibernate, Toplink, EclipseLink
www.freelancertech.net
ORM : Object Relational Mapping
Base de
donnée
MySQL
ORM
• Hibernate
• Toplink
• EclipseLink
Couche
DAO
JDBC
Pool de
Connexions
Objet image
de la BD
www.freelancertech.net
[1]
ReFactoring de la fonction enregistrée de notre couche DAO
www.freelancertech.net
Devant le succès des Frameworks ORM,
Sun a décidé de standardiser une couche ORM via une
spécification appelée JPA apparue en même temps que Java 5
www.freelancertech.net
JPA : Java Persistence Api
Base de
donnée
MySQL
Implémentation
• Hibernate
• Toplink
• EclipseLink
Couche
DAO
JDBC
Pool de
Connexions
[interface]
JPA
La spécification JPA est un ensemble d’interface du package
javax.persistence
[ EntityManager ]
void persist(Entity entité)
Exemple :
javax.persistence.Entity;
javax.persistence.EntityManagerFactory;
javax.persistence.EntityManager;
javax.persistence.EntityTransaction;
www.freelancertech.net
Refactoring de la fonction enregistrée de notre couche DAO
www.freelancertech.net
• JPA peut être utilisé par toutes les applications Java, Java
SE ou Java EE.
• Mapping O/R (objet-relationnel) avec les tables de la BD,
facilitée par les Annotations.
• Un langage de requête objet standard JPQL pour la
récupération des objets,
Ses principaux avantages sont les suivants :
JPA : Java Persistence Api
select p from Personne p order by p.nom asc
www.freelancertech.net
Entity: Entités
@Entity
@Table(name = "BOOK")
public class Book {
@Id
@GeneratedValue
private Long id;
@Column(name = "TITLE",nullable = false)
private String title;
private Float price;
@Basic(fetch = FetchType.LAZY)
@Column(length = 2000)
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations
//Les Getters et les Setters
[1]
Autres annotations
 Voir par exemple : JPA Reference
http://www.objectdb.com/api/java/jpa
 Les curieux peuvent consulter la spécification java
EE 6 ou le tutorial (ou un bon livre)
www.freelancertech.net
Contexte de persistance
Ensemble des instances d’entités gérées a un instant donné,
gérées par qui ? Le gestionnaire d’entités : EntityManager
Ce contexte peut donc être considéré comme un cache de
premier niveau : c’est un espace réduit ou le gestionnaire stocke
les entités avant d’écrire son contenu dans la base de données,
www.freelancertech.net
Opérations prises en charge par le
gestionnaire d’entités
NB : Un flush() est automatiquement effectué au moins à
chaque commit de la transaction en cours,
www.freelancertech.net
[2]
Cycle de vie d’une instance d’entité
www.freelancertech.net
[2]
Obtention d’une fabrique EntityManagerFactory
L’ interface EntityManagerFactory permet d’obtenir une instance de l’objet
EntityManager,
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa");
« jpa » est le nom de l’unité de persistance, définie dans le
fichier de configuration de la couche JPA METAINF/persistence.xml.
[3]
Création du gestionnaire d’entité
EntityManager
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa");
EntityManager em = emf.createEntityManager() ;
www.freelancertech.net
Exemple d’insertion d’un livre
public class Main {
public static void main(String[] args) {
// On crée une instance de livre
Book book = new Book();
book.setTitle("MUGC: JPAMYSQL");
book.setPrice(12.5F);
book.setDescription("Science fiction");
…
// On récupère un pointeur sur l’entity manager
// Remarque : dans une appli web, pas besoin de
faire tout cela !
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("jpa");
EntityManager em = emf.createEntityManager();
// On rend l’objet « persistant » dans la base (on
l’insère)
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(book);
tx.commit();
em.close();
emf.close();
}
Version Java SE Version Java EE
@Stateless
public class BookBean {
@PersistenceContext(unitName = "jpa")
private EntityManager em;
public void createBook() {
Book book = new Book();
book.setTitle("MUGC: JPAMYSQL");
book.setPrice(12.5F);
book.setDescription("Science fiction");
book.setIsbn("1-84023-742-2");
book.setNbOfPage(354);
book.setIllustrations(false);
em.persist(book);
// Récupère le livre dans la BD par sa clé
primaire
book = em.find(Book.class, 1234L);
System.out.println(book);
}
}
www.freelancertech.net
[1]
• La Persistence Unit : organise les meta
données qui définissent le mapping entre les
entités et la base de donnée dans le fichier de
configuration METAINF/persistence.xml
• La Persistence Manager Factory récupère
ces metas données de la Persistence Unit et
les interprètent pour créer des Persistence
Manager (EntityManager)
• Le Persistence Mangager (EntiyManager)
gère les échanges entre le code et la base de
donnée, c’est à dire le cycle de vie des entités
• Enfin, les opérations du EntityManager est
englobé dans une Transaction.
Fonctionnement de JPA
[4]
Relations entre entités
Relation un-à-un
@Entity
@Table(name = "jpa03_hb_personne")
public class Personne {
...
@OneToOne(cascade = CascadeType.ALL, fetch=FetchType.LAZY)
/*@OneToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST,
CascadeType.REFRESH, CascadeType.REMOVE}, fetch=FetchType.LAZY) */
@JoinColumn(name = "adresse_id", unique = true, nullable = false)
private Adresse adresse;
...
}
@Entity
@Table(name = "jpa03_hb_adresse")
public class Adresse{
...
/*n’est pas obligatoire*/
@OneToOne(mappedBy = "adresse", fetch=FetchType.EAGER)
private Personne personne;
...
}www.freelancertech.net
[3]
Relations entre entités
Relation un-à-plusieurs et plusieurs-à-un
@Entity
@Table(name="jpa05_hb_article")
public class Article{
...
// relation principale Article (many) -> Category (one) implémentée par une clé
// étrangère (categorie_id) dans Article
// 1 Article a nécessairement 1 Categorie (nullable=false)
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "categorie_id", nullable = false)
private Categorie categorie;
...
}
@Entity
@Table(name="jpa05_hb_categorie")
public class Categorie{
...
// relation inverse Categorie (one) -> Article (many) de la relation Article (many)– > Categorie (one)
@OneToMany(mappedBy = "categorie", cascade = { CascadeType.ALL })
private Set<Article> articles = new HashSet<Article>();
...
}
www.freelancertech.net
[3]
Relations entre entités
Relation un-à-plusieurs et plusieurs-à-un
@Entity
@Table(name="jpa06_hb_categorie")
public class Categorie{
...
// relation OneToMany non inverse (absence de mappedby) Categorie (one) -> Article (many)
// implémentée par une table de jointure Categorie_Article pour qu'à partir d'une catégorie
// on puisse atteindre plusieurs articles
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Article> articles = new HashSet<Article>();
...
}
www.freelancertech.net
[3]
Relations entre entités
Relation plusieurs-à-plusieurs
@Entity
@Table(name = "jpa07_hb_activite")
public class Activite{
...
// relation inverse Activite -> Personne
@ManyToMany(mappedBy = "activites")
private Set<Personne> personnes = new HashSet<Personne>();
...
}
@Entity
@Table(name = "jpa07_hb_personne")
public class Personne {
...
// relation Personne (many) -> Activite (many) via une table de jointure
personne_activite
@ManyToMany(cascade={CascadeType.PERSIST})
@JoinTable(name="jpa07_hb_personne_activite",
joinColumns = @JoinColumn(name = "PERSONNE_ID"),
inverseJoinColumns = @JoinColumn(name =
"ACTIVITE_ID"))
private Set<Activite> activites = new HashSet<Activite>();
...
}
pratiquer
www.freelancertech.net
[3]
Travaux pratiques
Génération des entités à partie d’une base de donnée MySQL
avec NetBean
www.freelancertech.net
Références
• [1] www.docstoc.com/docs/150704719/5--JPA-Michel-2012ppt
• [2] www.eyrolles.com/Chapitres/9782212120615/Chap10_Djaafar.pdf
• [3] www.tahe.ftp-developpez.com/fichiers-archive/jpa.pdf
• [4] www.blog.ippon.fr/2011/10/11/jpa-une-magie-qui-se-merite-retour-aux-sources-de-jpa/
www.freelancertech.net
Questions
www.freelancertech.net
Introduction à JPA  (Java Persistence API )

Weitere ähnliche Inhalte

Was ist angesagt?

Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...
Support de cours EJB 3 version complète Par Mr  Youssfi, ENSET, Université Ha...Support de cours EJB 3 version complète Par Mr  Youssfi, ENSET, Université Ha...
Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...ENSET, Université Hassan II Casablanca
 
L'API Collector dans tous ses états
L'API Collector dans tous ses étatsL'API Collector dans tous ses états
L'API Collector dans tous ses étatsJosé Paumard
 
Formation JPA Avancé / Hibernate gratuite par Ippon 2014
Formation JPA Avancé / Hibernate gratuite par Ippon 2014Formation JPA Avancé / Hibernate gratuite par Ippon 2014
Formation JPA Avancé / Hibernate gratuite par Ippon 2014Ippon
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldYura Nosenko
 
Spring boot anane maryem ben aziza syrine
Spring boot anane maryem ben aziza syrineSpring boot anane maryem ben aziza syrine
Spring boot anane maryem ben aziza syrineSyrine Ben aziza
 
Développement d'un site web jee de e commerce basé sur spring (m.youssfi)
Développement d'un site web jee de e commerce basé sur spring (m.youssfi)Développement d'un site web jee de e commerce basé sur spring (m.youssfi)
Développement d'un site web jee de e commerce basé sur spring (m.youssfi)ENSET, Université Hassan II Casablanca
 
Java entreprise edition et industrialisation du génie logiciel par m.youssfi
Java entreprise edition et industrialisation du génie logiciel par m.youssfiJava entreprise edition et industrialisation du génie logiciel par m.youssfi
Java entreprise edition et industrialisation du génie logiciel par m.youssfiENSET, Université Hassan II Casablanca
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentationJohn Slick
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework springAntoine Rey
 

Was ist angesagt? (20)

Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...
Support de cours EJB 3 version complète Par Mr  Youssfi, ENSET, Université Ha...Support de cours EJB 3 version complète Par Mr  Youssfi, ENSET, Université Ha...
Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
L'API Collector dans tous ses états
L'API Collector dans tous ses étatsL'API Collector dans tous ses états
L'API Collector dans tous ses états
 
Support JEE Spring Inversion de Controle IOC et Spring MVC
Support JEE Spring Inversion de Controle IOC et Spring MVCSupport JEE Spring Inversion de Controle IOC et Spring MVC
Support JEE Spring Inversion de Controle IOC et Spring MVC
 
Formation JPA Avancé / Hibernate gratuite par Ippon 2014
Formation JPA Avancé / Hibernate gratuite par Ippon 2014Formation JPA Avancé / Hibernate gratuite par Ippon 2014
Formation JPA Avancé / Hibernate gratuite par Ippon 2014
 
Cours design pattern m youssfi partie 5 adapter
Cours design pattern m youssfi partie 5 adapterCours design pattern m youssfi partie 5 adapter
Cours design pattern m youssfi partie 5 adapter
 
Cours design pattern m youssfi partie 3 decorateur
Cours design pattern m youssfi partie 3 decorateurCours design pattern m youssfi partie 3 decorateur
Cours design pattern m youssfi partie 3 decorateur
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 world
 
Spring boot anane maryem ben aziza syrine
Spring boot anane maryem ben aziza syrineSpring boot anane maryem ben aziza syrine
Spring boot anane maryem ben aziza syrine
 
Support POO Java première partie
Support POO Java première partieSupport POO Java première partie
Support POO Java première partie
 
Développement d'un site web jee de e commerce basé sur spring (m.youssfi)
Développement d'un site web jee de e commerce basé sur spring (m.youssfi)Développement d'un site web jee de e commerce basé sur spring (m.youssfi)
Développement d'un site web jee de e commerce basé sur spring (m.youssfi)
 
Les collections en Java
Les collections en JavaLes collections en Java
Les collections en Java
 
Maven et industrialisation du logiciel
Maven et industrialisation du logicielMaven et industrialisation du logiciel
Maven et industrialisation du logiciel
 
Java entreprise edition et industrialisation du génie logiciel par m.youssfi
Java entreprise edition et industrialisation du génie logiciel par m.youssfiJava entreprise edition et industrialisation du génie logiciel par m.youssfi
Java entreprise edition et industrialisation du génie logiciel par m.youssfi
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
Support de cours Spring M.youssfi
Support de cours Spring  M.youssfiSupport de cours Spring  M.youssfi
Support de cours Spring M.youssfi
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
spring-api-rest.pdf
spring-api-rest.pdfspring-api-rest.pdf
spring-api-rest.pdf
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework spring
 

Andere mochten auch

Rmi, corba and java beans
Rmi, corba and java beansRmi, corba and java beans
Rmi, corba and java beansRaghu nath
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)ejlp12
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8José Paumard
 
Alphorm.com Support de la formation JavaScript les fondamentaux
Alphorm.com Support de la formation JavaScript les fondamentauxAlphorm.com Support de la formation JavaScript les fondamentaux
Alphorm.com Support de la formation JavaScript les fondamentauxAlphorm
 
Alphorm.com Support de la formation Hacking & Sécurité, Expert - Vulnérabilit...
Alphorm.com Support de la formation Hacking & Sécurité, Expert - Vulnérabilit...Alphorm.com Support de la formation Hacking & Sécurité, Expert - Vulnérabilit...
Alphorm.com Support de la formation Hacking & Sécurité, Expert - Vulnérabilit...Alphorm
 
Les Streams sont parmi nous
Les Streams sont parmi nousLes Streams sont parmi nous
Les Streams sont parmi nousJosé Paumard
 
Entreprise Java Beans (EJB)
Entreprise Java Beans (EJB)Entreprise Java Beans (EJB)
Entreprise Java Beans (EJB)Heithem Abbes
 
Alphorm.com Formation Java,avancé OCP (1Z0-804)
Alphorm.com Formation Java,avancé OCP (1Z0-804)Alphorm.com Formation Java,avancé OCP (1Z0-804)
Alphorm.com Formation Java,avancé OCP (1Z0-804)Alphorm
 
Alphorm.com Formation Java, les fondamentaux
Alphorm.com Formation Java, les fondamentaux Alphorm.com Formation Java, les fondamentaux
Alphorm.com Formation Java, les fondamentaux Alphorm
 
alphorm.com - Formation HTML5, CSS 3 et JavaScript (70-480)
alphorm.com - Formation HTML5, CSS 3 et JavaScript (70-480)alphorm.com - Formation HTML5, CSS 3 et JavaScript (70-480)
alphorm.com - Formation HTML5, CSS 3 et JavaScript (70-480)Alphorm
 
alphorm.com - Formation UML
alphorm.com - Formation UMLalphorm.com - Formation UML
alphorm.com - Formation UMLAlphorm
 

Andere mochten auch (20)

Ejb3
Ejb3Ejb3
Ejb3
 
Rmi, corba and java beans
Rmi, corba and java beansRmi, corba and java beans
Rmi, corba and java beans
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)
 
Javascript et JQuery
Javascript et JQueryJavascript et JQuery
Javascript et JQuery
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8
 
Alphorm.com Support de la formation JavaScript les fondamentaux
Alphorm.com Support de la formation JavaScript les fondamentauxAlphorm.com Support de la formation JavaScript les fondamentaux
Alphorm.com Support de la formation JavaScript les fondamentaux
 
Alphorm.com Support de la formation Hacking & Sécurité, Expert - Vulnérabilit...
Alphorm.com Support de la formation Hacking & Sécurité, Expert - Vulnérabilit...Alphorm.com Support de la formation Hacking & Sécurité, Expert - Vulnérabilit...
Alphorm.com Support de la formation Hacking & Sécurité, Expert - Vulnérabilit...
 
Les Streams sont parmi nous
Les Streams sont parmi nousLes Streams sont parmi nous
Les Streams sont parmi nous
 
Entreprise Java Beans (EJB)
Entreprise Java Beans (EJB)Entreprise Java Beans (EJB)
Entreprise Java Beans (EJB)
 
Jquery mobile
Jquery mobileJquery mobile
Jquery mobile
 
Alphorm.com Formation Java,avancé OCP (1Z0-804)
Alphorm.com Formation Java,avancé OCP (1Z0-804)Alphorm.com Formation Java,avancé OCP (1Z0-804)
Alphorm.com Formation Java,avancé OCP (1Z0-804)
 
Alphorm.com Formation Java, les fondamentaux
Alphorm.com Formation Java, les fondamentaux Alphorm.com Formation Java, les fondamentaux
Alphorm.com Formation Java, les fondamentaux
 
alphorm.com - Formation HTML5, CSS 3 et JavaScript (70-480)
alphorm.com - Formation HTML5, CSS 3 et JavaScript (70-480)alphorm.com - Formation HTML5, CSS 3 et JavaScript (70-480)
alphorm.com - Formation HTML5, CSS 3 et JavaScript (70-480)
 
alphorm.com - Formation UML
alphorm.com - Formation UMLalphorm.com - Formation UML
alphorm.com - Formation UML
 
Ejb
Ejb Ejb
Ejb
 
Hibernate
HibernateHibernate
Hibernate
 
Support de Cours JSF2 Première partie Intégration avec Spring
Support de Cours JSF2 Première partie Intégration avec SpringSupport de Cours JSF2 Première partie Intégration avec Spring
Support de Cours JSF2 Première partie Intégration avec Spring
 
JPA est middleware
JPA est middleware JPA est middleware
JPA est middleware
 
Support POO Java Deuxième Partie
Support POO Java Deuxième PartieSupport POO Java Deuxième Partie
Support POO Java Deuxième Partie
 
Support Java Avancé Troisième Partie
Support Java Avancé Troisième PartieSupport Java Avancé Troisième Partie
Support Java Avancé Troisième Partie
 

Ähnlich wie Introduction à JPA (Java Persistence API )

Ähnlich wie Introduction à JPA (Java Persistence API ) (20)

Presentation JPA
Presentation JPAPresentation JPA
Presentation JPA
 
#5 Java EE5 Client Lourd et Smart Client
#5 Java EE5  Client Lourd  et Smart Client#5 Java EE5  Client Lourd  et Smart Client
#5 Java EE5 Client Lourd et Smart Client
 
Ado.net vs jpa
Ado.net vs jpaAdo.net vs jpa
Ado.net vs jpa
 
Springioc
SpringiocSpringioc
Springioc
 
jpa.pdf
jpa.pdfjpa.pdf
jpa.pdf
 
Spring Batch
Spring BatchSpring Batch
Spring Batch
 
Support cours j2_ee
Support cours j2_eeSupport cours j2_ee
Support cours j2_ee
 
Hibernate
HibernateHibernate
Hibernate
 
575
575575
575
 
Jdbc
JdbcJdbc
Jdbc
 
Hibernate
HibernateHibernate
Hibernate
 
react-slides.ppx (2) (1).pptx react presentation basic
react-slides.ppx (2) (1).pptx react presentation basicreact-slides.ppx (2) (1).pptx react presentation basic
react-slides.ppx (2) (1).pptx react presentation basic
 
Introduction à Hibernate p.1
Introduction à Hibernate p.1Introduction à Hibernate p.1
Introduction à Hibernate p.1
 
Jpa(1)
Jpa(1)Jpa(1)
Jpa(1)
 
Spring 3.0
Spring 3.0Spring 3.0
Spring 3.0
 
Linq et Entity framework
Linq et Entity frameworkLinq et Entity framework
Linq et Entity framework
 
Hibernate et jsf
Hibernate et jsfHibernate et jsf
Hibernate et jsf
 
La persistance des données : ORM et hibernate
La persistance des données : ORM et hibernateLa persistance des données : ORM et hibernate
La persistance des données : ORM et hibernate
 
[FR] Introduction à Spring Data Neo4j 3.x
[FR] Introduction à Spring Data Neo4j 3.x[FR] Introduction à Spring Data Neo4j 3.x
[FR] Introduction à Spring Data Neo4j 3.x
 
Présentation nouveauté java7
Présentation nouveauté java7Présentation nouveauté java7
Présentation nouveauté java7
 

Introduction à JPA (Java Persistence API )

  • 1. Introduction à JPA (Java Persistence API ) Fouomene Pewo Daniel Rene
  • 2. www.facebook.com/pages/FreelancerTech/822357474482862 www.twitter.com/FREELANCERTECH (@FREELANCERTECH) Une équipe d’experts dans leur domaine technologique qui ont décidé de se mettre ensemble pour offrir leurs services en fonction de leurs disponibilités, www.freelancertech.net
  • 3. • Historique • ORM : Object Relational Mapping • JPA : Java Persistence Api • Entity: Entités • Autres annotations • Contexte de persistance • Opérations prises en charge par le gestionnaire d’entités • Cycle de vie d’une instance d’entité • Obtention d’une fabrique EntityManagerFactory • Création du gestionnaire d’entité EntityManager • Exemple d’insertion d’un livre • Relations entre entités • Référence • Questions Plan www.freelancertech.net
  • 4. Base de donnée MySQL Couche DAO Couche Métier Couche UI JDBC Historique : Accès directement à la base de donnée grâce à l’API standard JDBC de Java
  • 5. • Pour des raisons de performances, le coût d'ouverture / fermeture d'une connexion n'est pas négligeable, o Connection con = DriverManager.getConnection(url, "login", "password"); o //les ordres SQL o con.close(); • L’utilisation du langage SQL rend la couche DAO difficilement maintenable, o String insertStatement = "Insert into Client(Nom, Prenom,Nature) values (?, ?, ?)" Problématiques de l’accès direct à la BD à l’aide de jdbc : www.freelancertech.net
  • 6. Pour pallier à cette problématique et faciliter l’écriture de la couche DAO, La communauté Java a donc fait naître des Frameworks ORM , tels que Hibernate, Toplink, EclipseLink www.freelancertech.net
  • 7. ORM : Object Relational Mapping Base de donnée MySQL ORM • Hibernate • Toplink • EclipseLink Couche DAO JDBC Pool de Connexions Objet image de la BD www.freelancertech.net [1]
  • 8. ReFactoring de la fonction enregistrée de notre couche DAO www.freelancertech.net
  • 9. Devant le succès des Frameworks ORM, Sun a décidé de standardiser une couche ORM via une spécification appelée JPA apparue en même temps que Java 5 www.freelancertech.net
  • 10. JPA : Java Persistence Api Base de donnée MySQL Implémentation • Hibernate • Toplink • EclipseLink Couche DAO JDBC Pool de Connexions [interface] JPA La spécification JPA est un ensemble d’interface du package javax.persistence [ EntityManager ] void persist(Entity entité) Exemple : javax.persistence.Entity; javax.persistence.EntityManagerFactory; javax.persistence.EntityManager; javax.persistence.EntityTransaction; www.freelancertech.net
  • 11. Refactoring de la fonction enregistrée de notre couche DAO www.freelancertech.net
  • 12. • JPA peut être utilisé par toutes les applications Java, Java SE ou Java EE. • Mapping O/R (objet-relationnel) avec les tables de la BD, facilitée par les Annotations. • Un langage de requête objet standard JPQL pour la récupération des objets, Ses principaux avantages sont les suivants : JPA : Java Persistence Api select p from Personne p order by p.nom asc www.freelancertech.net
  • 13. Entity: Entités @Entity @Table(name = "BOOK") public class Book { @Id @GeneratedValue private Long id; @Column(name = "TITLE",nullable = false) private String title; private Float price; @Basic(fetch = FetchType.LAZY) @Column(length = 2000) private String description; private String isbn; private Integer nbOfPage; private Boolean illustrations //Les Getters et les Setters [1]
  • 14. Autres annotations  Voir par exemple : JPA Reference http://www.objectdb.com/api/java/jpa  Les curieux peuvent consulter la spécification java EE 6 ou le tutorial (ou un bon livre) www.freelancertech.net
  • 15. Contexte de persistance Ensemble des instances d’entités gérées a un instant donné, gérées par qui ? Le gestionnaire d’entités : EntityManager Ce contexte peut donc être considéré comme un cache de premier niveau : c’est un espace réduit ou le gestionnaire stocke les entités avant d’écrire son contenu dans la base de données, www.freelancertech.net
  • 16. Opérations prises en charge par le gestionnaire d’entités NB : Un flush() est automatiquement effectué au moins à chaque commit de la transaction en cours, www.freelancertech.net [2]
  • 17. Cycle de vie d’une instance d’entité www.freelancertech.net [2]
  • 18. Obtention d’une fabrique EntityManagerFactory L’ interface EntityManagerFactory permet d’obtenir une instance de l’objet EntityManager, EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa"); « jpa » est le nom de l’unité de persistance, définie dans le fichier de configuration de la couche JPA METAINF/persistence.xml. [3]
  • 19. Création du gestionnaire d’entité EntityManager EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa"); EntityManager em = emf.createEntityManager() ; www.freelancertech.net
  • 20. Exemple d’insertion d’un livre public class Main { public static void main(String[] args) { // On crée une instance de livre Book book = new Book(); book.setTitle("MUGC: JPAMYSQL"); book.setPrice(12.5F); book.setDescription("Science fiction"); … // On récupère un pointeur sur l’entity manager // Remarque : dans une appli web, pas besoin de faire tout cela ! EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa"); EntityManager em = emf.createEntityManager(); // On rend l’objet « persistant » dans la base (on l’insère) EntityTransaction tx = em.getTransaction(); tx.begin(); em.persist(book); tx.commit(); em.close(); emf.close(); } Version Java SE Version Java EE @Stateless public class BookBean { @PersistenceContext(unitName = "jpa") private EntityManager em; public void createBook() { Book book = new Book(); book.setTitle("MUGC: JPAMYSQL"); book.setPrice(12.5F); book.setDescription("Science fiction"); book.setIsbn("1-84023-742-2"); book.setNbOfPage(354); book.setIllustrations(false); em.persist(book); // Récupère le livre dans la BD par sa clé primaire book = em.find(Book.class, 1234L); System.out.println(book); } } www.freelancertech.net [1]
  • 21. • La Persistence Unit : organise les meta données qui définissent le mapping entre les entités et la base de donnée dans le fichier de configuration METAINF/persistence.xml • La Persistence Manager Factory récupère ces metas données de la Persistence Unit et les interprètent pour créer des Persistence Manager (EntityManager) • Le Persistence Mangager (EntiyManager) gère les échanges entre le code et la base de donnée, c’est à dire le cycle de vie des entités • Enfin, les opérations du EntityManager est englobé dans une Transaction. Fonctionnement de JPA [4]
  • 22. Relations entre entités Relation un-à-un @Entity @Table(name = "jpa03_hb_personne") public class Personne { ... @OneToOne(cascade = CascadeType.ALL, fetch=FetchType.LAZY) /*@OneToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.REMOVE}, fetch=FetchType.LAZY) */ @JoinColumn(name = "adresse_id", unique = true, nullable = false) private Adresse adresse; ... } @Entity @Table(name = "jpa03_hb_adresse") public class Adresse{ ... /*n’est pas obligatoire*/ @OneToOne(mappedBy = "adresse", fetch=FetchType.EAGER) private Personne personne; ... }www.freelancertech.net [3]
  • 23. Relations entre entités Relation un-à-plusieurs et plusieurs-à-un @Entity @Table(name="jpa05_hb_article") public class Article{ ... // relation principale Article (many) -> Category (one) implémentée par une clé // étrangère (categorie_id) dans Article // 1 Article a nécessairement 1 Categorie (nullable=false) @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name = "categorie_id", nullable = false) private Categorie categorie; ... } @Entity @Table(name="jpa05_hb_categorie") public class Categorie{ ... // relation inverse Categorie (one) -> Article (many) de la relation Article (many)– > Categorie (one) @OneToMany(mappedBy = "categorie", cascade = { CascadeType.ALL }) private Set<Article> articles = new HashSet<Article>(); ... } www.freelancertech.net [3]
  • 24. Relations entre entités Relation un-à-plusieurs et plusieurs-à-un @Entity @Table(name="jpa06_hb_categorie") public class Categorie{ ... // relation OneToMany non inverse (absence de mappedby) Categorie (one) -> Article (many) // implémentée par une table de jointure Categorie_Article pour qu'à partir d'une catégorie // on puisse atteindre plusieurs articles @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Set<Article> articles = new HashSet<Article>(); ... } www.freelancertech.net [3]
  • 25. Relations entre entités Relation plusieurs-à-plusieurs @Entity @Table(name = "jpa07_hb_activite") public class Activite{ ... // relation inverse Activite -> Personne @ManyToMany(mappedBy = "activites") private Set<Personne> personnes = new HashSet<Personne>(); ... } @Entity @Table(name = "jpa07_hb_personne") public class Personne { ... // relation Personne (many) -> Activite (many) via une table de jointure personne_activite @ManyToMany(cascade={CascadeType.PERSIST}) @JoinTable(name="jpa07_hb_personne_activite", joinColumns = @JoinColumn(name = "PERSONNE_ID"), inverseJoinColumns = @JoinColumn(name = "ACTIVITE_ID")) private Set<Activite> activites = new HashSet<Activite>(); ... } pratiquer www.freelancertech.net [3]
  • 26. Travaux pratiques Génération des entités à partie d’une base de donnée MySQL avec NetBean www.freelancertech.net
  • 27. Références • [1] www.docstoc.com/docs/150704719/5--JPA-Michel-2012ppt • [2] www.eyrolles.com/Chapitres/9782212120615/Chap10_Djaafar.pdf • [3] www.tahe.ftp-developpez.com/fichiers-archive/jpa.pdf • [4] www.blog.ippon.fr/2011/10/11/jpa-une-magie-qui-se-merite-retour-aux-sources-de-jpa/ www.freelancertech.net