SlideShare une entreprise Scribd logo
1  sur  58
Télécharger pour lire hors ligne
´
Developpement Web - Object Relational Mapping and Hibernate

´
Developpement Web - Object Relational
Mapping and Hibernate
Jean-Michel Richer
jean-michel.richer@univ-angers.fr
http://www.info.univ-angers.fr/pub/richer

M1/M2 Informatique 2010-2011
1 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Plan

Plan

1

Introduction

2

JOBYME

3

Hibernate

4

Bibliographie

2 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Plan

ORM et Hibernate

Objectifs
• se familiariser avec l’ORM
• le mettre en oeuvre sans framework (jobyme)
• le mettre en oeuvre en utilisant Hibernate

3 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Introduction

Introduction

Introduction

4 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Introduction

Que’est-ce que l’ORM ?

ORM
´
L’ORM ou Object Relational Mapping a pour but d’etablir la
correspondance entre
• une table de la base de donnees
´
• et une classe du modele objet
`

5 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Introduction

Pourquoi l’ORM ?

´
´
Necessite de l’ORM
• le modele logique des donnees est different du modele de
`
´
´
`
classe
• reutilisabilite du code pour effectuer les operation de base :
´
´
´
• DAO
• CRUD

6 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Introduction

Rappel CRUD

CRUD
`
ensemble des fonctions a implanter dans un BD relationnelle :
´
Operation
Create
Read (Retrieve)
Update
Delete (Destroy)

SQL
INSERT
SELECT
UPDATE
DELETE

7 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Introduction

Pourquoi l’ORM ?

Comparaison Objet et Relationnel
´
La representation sous forme Relationnelle n’entre pas en
´
correspondance avec la representation Objet
• Objet : notions d’heritage et de polymorphisme
´
• Objet : pas d’identifiant (pointeur)
• Objet : les relations n:m sont modelisees par des
´ ´

containers

8 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Introduction

ORM et Java

ORM et Java
´
´ `
Inconvenients lies a Java
• choix important de solutions et outils / API
• evolution des API suivant les versions :
´
• difficulte d’apprentissage
´
• difficulte de configuration
´

9 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Introduction

ORM et Java

ORM, Java et JDBC
´
la JDBC (Java DataBase Connectivity) a apporte une
`
´
standardisation au niveau de l’acces des bases de donnees,
mais :
• il faut ecrire le code pour realiser le CRUD
´
´
• et realiser le mapping entre tables et objets
´

10 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Introduction

ORM et Java

Solutions existantes
• API standard : JDO (Java Data Objects + POJO)
• API : Hibernate + POJO
• API complexes : EJB Entity

Frameworks de persistance : http://fr.wikipedia.org
(Hibernate, Cayenne, EJB3, ...

11 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Introduction

ORM et Java

Comparaison JDO et Hibernate
• JDO est un standard et Hibernate une solution Open

Source
• JDO peut traiter la persistance des BD Objets ou XML

(possible depuis Hibernate 3)
• JDO propose un langage de requete JDOQL / HSQL
ˆ
• JDO modifie les POJO alors que ce n’est pas le cas

d’Hibernate

12 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Introduction

ORM et Java

JDO
• www.oracle.com
• http://db.apache.org/jdo/index.html

Hibernate
• http://www.hibernate.org/

13 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

JOBYME

JOBYME

14 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

JOBYME

´
Definition JOBYME
• Java Orm BY ME
• tentative de generation automatique de l’ORM (Code Java
´ ´
+ CRUD)
• lecture de la BD (MySQL) et generation du code
´ ´
correspondant

15 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

Etude de cas

Etude de cas
´
´
On desire modeliser la relation : Client, Commande, Produit
(Customer, Command, Product).

16 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

Conventions de nommage

´
Conventions de nommage des entites
• tout en minuscule, separation par caractere souligne ( )
´
`
´
• table : meme nom que l’entite (customer)
ˆ
´
• attributs : prefixes par les 2 premiers caracteres de la
´ ´
`

`
´
table et caractere souligne (cu )
• toujours un identifiant (cu id)
• minimiser la longueur des champs
• faire en sorte que leurs noms soient explicites

17 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

Cas de la table commande

Cas de la table commande
champ
co id
co date
co total price
co cu id

ˆ
role
identifiant
´
date creation
prix total
identifiant client

type
integer
date
float
integer

index
PK
NX
NX

18 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

Conventions de nommage

Conventions de nommage des relations n/m
• par ordre alphabetique du nom des entites / tables
´
´
• nom : 4 premieres lettres de la premiere table, 4 premieres
`
`
`

lettres
• prefixe : premieres lettres des entites
´
`
´

19 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

Cas de la relation commande / produit

Relation commande / produit : commprod
champ
cp id
cp co id
co pr id
cp qty

ˆ
role
identifiant
identifiant commande
identifiant produit
´
quantite

type
integer
integer
integer
integer

index
PK
NX
NX

20 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

JOBYME

´
Installation de la base de donnees
´
Mettre en place la base de donnees commands.sql sous
MySQL :
• nom de la base : commands
• identifiant de connexion : commuser
• mot de passe : commpass

21 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

Mapping Objet / Relationnel

Mise en correspondance objet / tuple
´
´
realisee au travers d’un fichier de description des tables
´
´ `
´
nomme mapping.xml place a la racine du projet. On decrit le
´
nom de la table et le nom de la classe associee :
• table : nom de la table
• class : nom de la classe
• prefix : prefixe du nom de table
´

22 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

Mapping Objet / Relationnel

Mise en correspondance relation / attribut
´
on decrit ensuite les relations :
• type : type de relation (one-to-one, one-to-many)
• attribute : nom de l’attribut
• class : nom de la classe associee
´
• crud : liste des operations a effectuer
´
`

(create,retrieve*,update,delete)
(*) en cascade

23 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

DTD du Mapping

DTD Mapping Objet / Relationnel
1
2
3
4
5
6
7
8
9
10
11
12

<?xml version="1.0" encoding="utf-8" ?>
<!ELEMENT mappings (mapping+) >
<!ELEMENT mapping (relation*) >
<!ATTLIST mapping table CDATA #REQUIRED >
<!ATTLIST mapping class CDATA #REQUIRED >
<!ATTLIST mapping prefix CDATA #REQUIRED >
<!ELEMENT relation EMPTY >
<!ATTLIST relation type CDATA #REQUIRED >
<!ATTLIST relation attribute CDATA #REQUIRED >
<!ATTLIST relation class CDATA #REQUIRED >
<!ATTLIST relation crud CDATA #REQUIRED >

24 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

Exemple

Customer, Command, Product

25 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

Mapping
Mapping Objet / Relationnel
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mappings SYSTEM "mappings.dtd">
<mappings>
<mapping table="command" class="Command" prefix="co">
<relation type="one-to-one" attribute="customer" class="Customer"'
crud="retrieve" />
<relation type="one-to-many" attribute="commprods" class="Commprod"'
crud="create,retrieve*,update,delete" />
</mapping>
<mapping table="customer" class="Customer" prefix="cu">
<relation type="one-to-many" attribute="commands" class="Command"'
crud="retrieve" />
</mapping>
<mapping table="commprod" class="Commprod" prefix="cp">
<relation type="one-to-one" attribute="product" class="Product"'
crud="retrieve" />
</mapping>
<mapping table="product" class="Product" prefix="pr" />
</mappings>

26 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

`
´ ´ ´
Modele objet genere

La classe Command
1 public class Command extends PersistentObject
2
implements PersistentInterface {
3
protected int id;
4
5
protected String date;
6
protected int cuId;
7
protected float totalPrice;
8
protected int nbCmdlines;
9
// relational fields
10
protected Customer customer;
11
protected List<Commprod> commprods;
12 }

27 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

`
´ ´ ´
Modele objet genere

La classe Customer
1 public class Customer extends PersistentObject
2
implements PersistentInterface {
3
protected int id;
4
5
protected String firstName;
6
protected String lastName;
7
protected String email;
8
protected String password;
9
protected int rights;
10
// relational fields
11
protected List<Command> commands;
12 }

28 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

Persistance
Mise en place de la persistance

29 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

Persistance

Mise en place de la persistance

30 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
JOBYME

Utilisation de JOBYME

Utiliser JOBYME
´
dans le repertoire du projet lancer : ant
• compile le generateur
´ ´
• genere les classes a partir du fichier de mapping
´ ´
`
• lance un test sommaire

31 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Hibernate

Hibernate

32 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Hibernate

Hibernate
• framework ORM pour Java (BD Relationnelles et Objet)
• requetes pour CRUD (HQL Hibernate Query Language)
ˆ
• utilisation des POJOs (Plain Old Java Objects)
• configuration au travers de fichiers XML ou d’annotations
• tres fortement configurable
`
• tres difficile a maˆtriser !
`
`
ı

33 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Historique

Hibernate
• 2001 par Gavin King, alternative a EJB2
`
• 2003 version 2 qui devient un standard incontournable
• integration JBOSS (RedHat)
´
• 2010 version 3 : annotations

34 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Mapping Hibernate

Utilisation des mappings
• par convention l’extension est .hbm.xml
• on definit un fichier par classe / table
´
• placer le fichier de mapping dans le meme repertoire que
ˆ
´

le fichier de classe

35 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Mapping Hibernate

fichier Mapping NomClasse.hbm.xml
• permet de faire le lien entre les champs de la table et ceux

de la classe
• doit etre declare dans le repertoire de la classe
ˆ
´
´
´

example Product
´
´
Product.hbm.xml declare dans com.mysite.model

36 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Mapping Hibernate
`
´
Modele de declaration
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.commands.model">
<class name="Product" table="product">
<id name="id" type="integer" column="pr id">
<generator class="native"/>
</id>
<property name="label" column="pr label"/>
<property name="stock" type="int" column="pr stock"/>
<property name="price" type="float" column="pr price"/>
</class>
</hibernate-mapping>

37 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Mapping Hibernate

Structure du mapping
1
2
3
4
5
6
7
8
9
10
11
12
13

<hibernate-mapping package="PackageName">
<class
name="ClassName"
table="tableName"
lazy="true|false"
polymorphism="implicit|explicit"
where="arbitrary sql where condition"
rowid="rowid"
subselect="SQL expression"
...
>
...
</hibernate-mapping>

38 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Mapping Hibernate

Structure du Mapping
• PackageName : nom du package ou se trouve la classe
• ClassName : nom de la classe Java
• tableName : nom de la table de la base de donnees
´
• autres parametres a definir selon la base de donnees et
`
` ´
´

l’environnement

39 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Mapping Hibernate

´
Definition des champs de la table
• id : permet de definir l’identifiant de la table
´
• property : champ simple
• composite-id : cle composee
´
´
• timestamp : champ de type date/heure

40 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Mapping Hibernate

Structure d’un identifiant
1 <id
2
3
4
5
6
7
8
9
10 </id>
11

name="propertyName"
type="typename"
column="column name"
unsaved-value="null|any|none|undefined|id value"
access="field|property|ClassName">
node="element-name|@attribute-name|element/@attribute|."
<generator class="generatorClass"/>

41 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Mapping Hibernate

´
Definition d’un identifiant
• name : nom du champ de la classe
• type : integer, long, float, string, character, timestamp,

binary, ...
• column : nom du champ dans la table
• generator : methode de generation de l’identifiant
´
´ ´

42 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Mapping Hibernate

´
´ ´
Methode de generation d’un identifiant
• assigned : l’utilisateur est responsable de la generation
´ ´
• native : la base de donnees est responsable de la
´

´ ´
generation

43 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Mapping Hibernate
´ ´
Structure d’une propriete
1 <property
2
name="propertyName"
3
column="column name"
4
type="typename"
5
update="true|false"
6
insert="true|false"
7
formula="arbitrary SQL expression"
8
access="field|property|ClassName"
9
lazy="true|false"
10
unique="true|false"
11
not-null="true|false"
12
index="index name"
13
unique key="unique key id"
14
length="L"
15
precision="P"
16
scale="S"
17 />

44 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Mapping Hibernate

´
´ ´
Definition d’une propriete
• name, type, column
• update, insert : indique que le champ doit etre ajoute lors
ˆ
´

´
`
d’une modification ou insertion (defaut a vrai)
• formula : expression SQL qui permet de definir le champ
´
• lazy : acces aux objets associes
`
´

45 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

´
Strategies de chargement

Fetching
• concerne le chargement des objets lies par des relations
´
• probleme complexe pour assurer l’efficacite
`
´

Exemple : chargement d’un client
Faut-il charger toutes les commandes lors du chargement du
client ?

46 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

´
Strategies de chargement

Fetching strategies
´
´
Hibernate definit 4 strategies de chargement
• Immediate
• Lazy : ne charge pas tout
• Eager : on specifie quels objets doivent etre charges
´
ˆ
´
• Batch

47 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Utiliser Hibernate

Utilisation de Hibernate
• definir un fichier de configuration
´
• demarrer Hibernate requiert la creation d’une
´
´

SessionFactory

48 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Fichier de configuration

Fichier de configuration hibernate.cfg.xml
• definit les parametres d’acces a la base de donnees
´
`
` `
´
• definit ou trouver les fichiers de mapping (ressource)
´
`
• doit etre place dans le repertoire src du projet
ˆ
´
´

49 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Configuration d’Hibernate
Fichier de configuration hibernate.cfg.xml
1 <hibernate-configuration>
2
<session-factory>
3
<!-- Database connection settings -->
4
<property name="connection.driver class">com.mysql.jdbc.Driver<'
5
/property>
6
<property name="connection.url">jdbc:mysql://localhost:3306/commands<'
7
/property>
8
<property name="connection.username">commuser</property>
9
<property name="connection.password">commpass</property>
10
<!-- JDBC connection pool (use the built-in) -->
11
<property name="connection.pool size">1</property>
12
<!-- SQL dialect -->
13
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
14
<!-- Enable Hibernate’s automatic session context management -->
15
<property name="current session context class">thread</property>
16
<!-- Disable the second-level cache -->
17
<property name="cache.provider class">org.hibernate.cache.'
18
NoCacheProvider</property>
19
<!-- Echo all executed SQL to stdout -->
20
<property name="show sql">true</property>
21
<mapping resource="com/mysite/model/command.hbm.xml"/>
22
</session-factory>
23 </hibernate-configuration>
24
25
50 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

SessionFactory

classe HibernateUtil
• obtenir une instance de SessionFactory
• realise l’initialisation de la connexion
´

51 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

HibernateUtil
HibernateUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import static java.lang.System.err;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory()'
;
} catch (Exception ex) {
// Make sure you log the exception, as it might be swallowed
err.println("Initial SessionFactory creation failed." + ex.getMessage('
));
throw new ExceptionInInitializerError(ex.getMessage());
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

52 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Librairies .jar

Librairies Hibernate
´
Mettre dans le repertoire WEB-INF/lib ou lib :
• l’ensemble des fichiers de Hibernate lib/required
• ajouter egalement slf4j-simple
´

http://www.slf4j.org/

53 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

HibernateUtil

Application
´
Mettre en place la configuration JAVA pour realiser un test avec
Hibernate

54 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Hibernate et annotations

Annotations
`
´
Hibernate integre un mecanisme d’annotation qui permet de
remplacer les fichiers de mapping par des commentaires dans
le code. L’objectif est de
• ne pas separer le code Java du fichier de mapping
´
• de maniere a configurer Hibernate automatiquement
` `

55 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Hibernate

Exemple d’annotations
Annotations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

import org.hibernate.annotations.Index;
@Entity
@Table(name="ARTIST")
@NamedQueries({
@NamesQuery(name="com.oreilly.hh.artistByName",
query="from Artist as artist where upper(artist.name)=upper(:name)")
})
public class Artist {
@Id
@Column(name="ARTIST ID")
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@Column(name="NAME",nullable=false,unique=true)
@Index(name="ARTIST NAME",columnNames={"NAME"})
private String name;
@ManyToMany
@JoinTable(name="TRACK ARTISTS",
joinColumns={@JoinColumn(name="TRACK ID")},
inverseJoinColumns={@JoinColumn(name="ARTIST ID")})
private Set<Track> tracks;
}

56 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Bibliographie

Bibliographie

Bibliographie

57 / 58
´
Developpement Web - Object Relational Mapping and Hibernate
Bibliographie

Bibliographie, sitographie

• Hibernate Quickly, Patrick Peak, Nick Heudecker,

Manning, 2006
• Hibernate in Action, Christian Bauer, Gavin King,

Manning, 2005
• Harnessing Hibernate, James Elliot, Tim O’Brien, Ryan

Fowler, O’Reilly, 2008
• www.hibernate.org

58 / 58

Contenu connexe

Tendances (15)

Jpa(1)
Jpa(1)Jpa(1)
Jpa(1)
 
Hibernate
HibernateHibernate
Hibernate
 
Support JEE Servlet Jsp MVC M.Youssfi
Support JEE Servlet Jsp MVC M.YoussfiSupport JEE Servlet Jsp MVC M.Youssfi
Support JEE Servlet Jsp MVC M.Youssfi
 
Objet Direct Formation JPA Hibernate
Objet Direct Formation JPA HibernateObjet Direct Formation JPA Hibernate
Objet Direct Formation JPA Hibernate
 
Jpa Spring Hibernate
Jpa Spring HibernateJpa Spring Hibernate
Jpa Spring Hibernate
 
Support de cours angular
Support de cours angularSupport de cours angular
Support de cours angular
 
Cours javascript
Cours javascriptCours javascript
Cours javascript
 
4 Hibernate
4 Hibernate4 Hibernate
4 Hibernate
 
Cours JavaScript
Cours JavaScriptCours JavaScript
Cours JavaScript
 
Introduction au Domain Driven Design
Introduction au Domain Driven DesignIntroduction au Domain Driven Design
Introduction au Domain Driven Design
 
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...
 
Hibernate et jsf
Hibernate et jsfHibernate et jsf
Hibernate et jsf
 
J2 ee
J2 eeJ2 ee
J2 ee
 
Aspect avec AspectJ
Aspect avec AspectJAspect avec AspectJ
Aspect avec AspectJ
 
Présentation de JEE et de son écosysteme
Présentation de JEE et de son écosystemePrésentation de JEE et de son écosysteme
Présentation de JEE et de son écosysteme
 

Similaire à ORM

Codedarmor 2012 - 06/03 - HTML5, CSS3 et Javascript
Codedarmor 2012 - 06/03 - HTML5, CSS3 et JavascriptCodedarmor 2012 - 06/03 - HTML5, CSS3 et Javascript
Codedarmor 2012 - 06/03 - HTML5, CSS3 et Javascriptcodedarmor
 
D’un modèle d'IA dans un notebook à un service temps réel : architecturons !
D’un modèle d'IA dans un notebook à un service temps réel : architecturons ! D’un modèle d'IA dans un notebook à un service temps réel : architecturons !
D’un modèle d'IA dans un notebook à un service temps réel : architecturons ! Marie-Alice Blete
 
SPA avec Angular et SignalR (FR)
SPA avec Angular et SignalR (FR)SPA avec Angular et SignalR (FR)
SPA avec Angular et SignalR (FR)Rui Carvalho
 
Comment reprendre un (gros) projet Ruby on Rails
Comment reprendre un (gros) projet Ruby on RailsComment reprendre un (gros) projet Ruby on Rails
Comment reprendre un (gros) projet Ruby on RailsNovelys
 
Une visite guidée d’Internet Explorer 9 et HTML5 pour les développeurs Web
Une visite guidée d’Internet Explorer 9 et HTML5 pour les développeurs WebUne visite guidée d’Internet Explorer 9 et HTML5 pour les développeurs Web
Une visite guidée d’Internet Explorer 9 et HTML5 pour les développeurs WebFrédéric Harper
 
S2-01-PHP.pptx
S2-01-PHP.pptxS2-01-PHP.pptx
S2-01-PHP.pptxkohay75604
 
Les dernières avancées HTML5 & CSS3 en action !
Les dernières avancées HTML5 & CSS3 en action !Les dernières avancées HTML5 & CSS3 en action !
Les dernières avancées HTML5 & CSS3 en action !Microsoft Technet France
 
Les dernières avancées html5 & css3 en action !
Les dernières avancées html5 & css3 en action !Les dernières avancées html5 & css3 en action !
Les dernières avancées html5 & css3 en action !davrous
 
Spark-adabra, Comment Construire un DATALAKE ! (Devoxx 2017)
Spark-adabra, Comment Construire un DATALAKE ! (Devoxx 2017) Spark-adabra, Comment Construire un DATALAKE ! (Devoxx 2017)
Spark-adabra, Comment Construire un DATALAKE ! (Devoxx 2017) univalence
 
Dotnet j2 ee
Dotnet j2 eeDotnet j2 ee
Dotnet j2 eechdalel
 
Formation d'architecte logiciel AFCEPF
Formation d'architecte logiciel AFCEPFFormation d'architecte logiciel AFCEPF
Formation d'architecte logiciel AFCEPFBoubker ABERWAG
 
Retours Devoxx France 2016
Retours Devoxx France 2016Retours Devoxx France 2016
Retours Devoxx France 2016Antoine Rey
 
Linq et Entity framework
Linq et Entity frameworkLinq et Entity framework
Linq et Entity frameworkDNG Consulting
 
Clean Architecture et Code patrimonial
Clean Architecture et Code patrimonialClean Architecture et Code patrimonial
Clean Architecture et Code patrimonialAgile Montréal
 
HTML5... La révolution maintenant!
HTML5... La révolution maintenant!HTML5... La révolution maintenant!
HTML5... La révolution maintenant!CARA_Lyon
 
HTML5... La révolution maintenant!
HTML5... La révolution maintenant!HTML5... La révolution maintenant!
HTML5... La révolution maintenant!CARA_Lyon
 
Parisweb - javascript server side - par où commencer ?
Parisweb - javascript server side - par où commencer ?Parisweb - javascript server side - par où commencer ?
Parisweb - javascript server side - par où commencer ?Quentin Adam
 
ENIB cours CAI Web - Séance 4 - Frameworks/Spring - Cours
ENIB cours CAI Web - Séance 4 - Frameworks/Spring - CoursENIB cours CAI Web - Séance 4 - Frameworks/Spring - Cours
ENIB cours CAI Web - Séance 4 - Frameworks/Spring - CoursHoracio Gonzalez
 

Similaire à ORM (20)

Codedarmor 2012 - 06/03 - HTML5, CSS3 et Javascript
Codedarmor 2012 - 06/03 - HTML5, CSS3 et JavascriptCodedarmor 2012 - 06/03 - HTML5, CSS3 et Javascript
Codedarmor 2012 - 06/03 - HTML5, CSS3 et Javascript
 
D’un modèle d'IA dans un notebook à un service temps réel : architecturons !
D’un modèle d'IA dans un notebook à un service temps réel : architecturons ! D’un modèle d'IA dans un notebook à un service temps réel : architecturons !
D’un modèle d'IA dans un notebook à un service temps réel : architecturons !
 
SPA avec Angular et SignalR (FR)
SPA avec Angular et SignalR (FR)SPA avec Angular et SignalR (FR)
SPA avec Angular et SignalR (FR)
 
_JCVFr
_JCVFr_JCVFr
_JCVFr
 
Comment reprendre un (gros) projet Ruby on Rails
Comment reprendre un (gros) projet Ruby on RailsComment reprendre un (gros) projet Ruby on Rails
Comment reprendre un (gros) projet Ruby on Rails
 
Une visite guidée d’Internet Explorer 9 et HTML5 pour les développeurs Web
Une visite guidée d’Internet Explorer 9 et HTML5 pour les développeurs WebUne visite guidée d’Internet Explorer 9 et HTML5 pour les développeurs Web
Une visite guidée d’Internet Explorer 9 et HTML5 pour les développeurs Web
 
S2-01-PHP.pptx
S2-01-PHP.pptxS2-01-PHP.pptx
S2-01-PHP.pptx
 
Les dernières avancées HTML5 & CSS3 en action !
Les dernières avancées HTML5 & CSS3 en action !Les dernières avancées HTML5 & CSS3 en action !
Les dernières avancées HTML5 & CSS3 en action !
 
Les dernières avancées html5 & css3 en action !
Les dernières avancées html5 & css3 en action !Les dernières avancées html5 & css3 en action !
Les dernières avancées html5 & css3 en action !
 
Spark-adabra, Comment Construire un DATALAKE ! (Devoxx 2017)
Spark-adabra, Comment Construire un DATALAKE ! (Devoxx 2017) Spark-adabra, Comment Construire un DATALAKE ! (Devoxx 2017)
Spark-adabra, Comment Construire un DATALAKE ! (Devoxx 2017)
 
Dotnet j2 ee
Dotnet j2 eeDotnet j2 ee
Dotnet j2 ee
 
Formation d'architecte logiciel AFCEPF
Formation d'architecte logiciel AFCEPFFormation d'architecte logiciel AFCEPF
Formation d'architecte logiciel AFCEPF
 
Retours Devoxx France 2016
Retours Devoxx France 2016Retours Devoxx France 2016
Retours Devoxx France 2016
 
Linq et Entity framework
Linq et Entity frameworkLinq et Entity framework
Linq et Entity framework
 
Clean Architecture et Code patrimonial
Clean Architecture et Code patrimonialClean Architecture et Code patrimonial
Clean Architecture et Code patrimonial
 
HTML5... La révolution maintenant!
HTML5... La révolution maintenant!HTML5... La révolution maintenant!
HTML5... La révolution maintenant!
 
HTML5... La révolution maintenant!
HTML5... La révolution maintenant!HTML5... La révolution maintenant!
HTML5... La révolution maintenant!
 
Gradle_LyonJUG
Gradle_LyonJUGGradle_LyonJUG
Gradle_LyonJUG
 
Parisweb - javascript server side - par où commencer ?
Parisweb - javascript server side - par où commencer ?Parisweb - javascript server side - par où commencer ?
Parisweb - javascript server side - par où commencer ?
 
ENIB cours CAI Web - Séance 4 - Frameworks/Spring - Cours
ENIB cours CAI Web - Séance 4 - Frameworks/Spring - CoursENIB cours CAI Web - Séance 4 - Frameworks/Spring - Cours
ENIB cours CAI Web - Séance 4 - Frameworks/Spring - Cours
 

Plus de angeeLee

Plus de angeeLee (9)

ORM
ORMORM
ORM
 
ORM
ORMORM
ORM
 
ORM
ORMORM
ORM
 
ORM
ORMORM
ORM
 
ORM
ORMORM
ORM
 
ORM
ORMORM
ORM
 
UML
UMLUML
UML
 
UML
UMLUML
UML
 
Cours services web_fabrice_mourlin
Cours services web_fabrice_mourlinCours services web_fabrice_mourlin
Cours services web_fabrice_mourlin
 

ORM

  • 1. ´ Developpement Web - Object Relational Mapping and Hibernate ´ Developpement Web - Object Relational Mapping and Hibernate Jean-Michel Richer jean-michel.richer@univ-angers.fr http://www.info.univ-angers.fr/pub/richer M1/M2 Informatique 2010-2011 1 / 58
  • 2. ´ Developpement Web - Object Relational Mapping and Hibernate Plan Plan 1 Introduction 2 JOBYME 3 Hibernate 4 Bibliographie 2 / 58
  • 3. ´ Developpement Web - Object Relational Mapping and Hibernate Plan ORM et Hibernate Objectifs • se familiariser avec l’ORM • le mettre en oeuvre sans framework (jobyme) • le mettre en oeuvre en utilisant Hibernate 3 / 58
  • 4. ´ Developpement Web - Object Relational Mapping and Hibernate Introduction Introduction Introduction 4 / 58
  • 5. ´ Developpement Web - Object Relational Mapping and Hibernate Introduction Que’est-ce que l’ORM ? ORM ´ L’ORM ou Object Relational Mapping a pour but d’etablir la correspondance entre • une table de la base de donnees ´ • et une classe du modele objet ` 5 / 58
  • 6. ´ Developpement Web - Object Relational Mapping and Hibernate Introduction Pourquoi l’ORM ? ´ ´ Necessite de l’ORM • le modele logique des donnees est different du modele de ` ´ ´ ` classe • reutilisabilite du code pour effectuer les operation de base : ´ ´ ´ • DAO • CRUD 6 / 58
  • 7. ´ Developpement Web - Object Relational Mapping and Hibernate Introduction Rappel CRUD CRUD ` ensemble des fonctions a implanter dans un BD relationnelle : ´ Operation Create Read (Retrieve) Update Delete (Destroy) SQL INSERT SELECT UPDATE DELETE 7 / 58
  • 8. ´ Developpement Web - Object Relational Mapping and Hibernate Introduction Pourquoi l’ORM ? Comparaison Objet et Relationnel ´ La representation sous forme Relationnelle n’entre pas en ´ correspondance avec la representation Objet • Objet : notions d’heritage et de polymorphisme ´ • Objet : pas d’identifiant (pointeur) • Objet : les relations n:m sont modelisees par des ´ ´ containers 8 / 58
  • 9. ´ Developpement Web - Object Relational Mapping and Hibernate Introduction ORM et Java ORM et Java ´ ´ ` Inconvenients lies a Java • choix important de solutions et outils / API • evolution des API suivant les versions : ´ • difficulte d’apprentissage ´ • difficulte de configuration ´ 9 / 58
  • 10. ´ Developpement Web - Object Relational Mapping and Hibernate Introduction ORM et Java ORM, Java et JDBC ´ la JDBC (Java DataBase Connectivity) a apporte une ` ´ standardisation au niveau de l’acces des bases de donnees, mais : • il faut ecrire le code pour realiser le CRUD ´ ´ • et realiser le mapping entre tables et objets ´ 10 / 58
  • 11. ´ Developpement Web - Object Relational Mapping and Hibernate Introduction ORM et Java Solutions existantes • API standard : JDO (Java Data Objects + POJO) • API : Hibernate + POJO • API complexes : EJB Entity Frameworks de persistance : http://fr.wikipedia.org (Hibernate, Cayenne, EJB3, ... 11 / 58
  • 12. ´ Developpement Web - Object Relational Mapping and Hibernate Introduction ORM et Java Comparaison JDO et Hibernate • JDO est un standard et Hibernate une solution Open Source • JDO peut traiter la persistance des BD Objets ou XML (possible depuis Hibernate 3) • JDO propose un langage de requete JDOQL / HSQL ˆ • JDO modifie les POJO alors que ce n’est pas le cas d’Hibernate 12 / 58
  • 13. ´ Developpement Web - Object Relational Mapping and Hibernate Introduction ORM et Java JDO • www.oracle.com • http://db.apache.org/jdo/index.html Hibernate • http://www.hibernate.org/ 13 / 58
  • 14. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME JOBYME JOBYME 14 / 58
  • 15. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME JOBYME ´ Definition JOBYME • Java Orm BY ME • tentative de generation automatique de l’ORM (Code Java ´ ´ + CRUD) • lecture de la BD (MySQL) et generation du code ´ ´ correspondant 15 / 58
  • 16. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME Etude de cas Etude de cas ´ ´ On desire modeliser la relation : Client, Commande, Produit (Customer, Command, Product). 16 / 58
  • 17. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME Conventions de nommage ´ Conventions de nommage des entites • tout en minuscule, separation par caractere souligne ( ) ´ ` ´ • table : meme nom que l’entite (customer) ˆ ´ • attributs : prefixes par les 2 premiers caracteres de la ´ ´ ` ` ´ table et caractere souligne (cu ) • toujours un identifiant (cu id) • minimiser la longueur des champs • faire en sorte que leurs noms soient explicites 17 / 58
  • 18. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME Cas de la table commande Cas de la table commande champ co id co date co total price co cu id ˆ role identifiant ´ date creation prix total identifiant client type integer date float integer index PK NX NX 18 / 58
  • 19. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME Conventions de nommage Conventions de nommage des relations n/m • par ordre alphabetique du nom des entites / tables ´ ´ • nom : 4 premieres lettres de la premiere table, 4 premieres ` ` ` lettres • prefixe : premieres lettres des entites ´ ` ´ 19 / 58
  • 20. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME Cas de la relation commande / produit Relation commande / produit : commprod champ cp id cp co id co pr id cp qty ˆ role identifiant identifiant commande identifiant produit ´ quantite type integer integer integer integer index PK NX NX 20 / 58
  • 21. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME JOBYME ´ Installation de la base de donnees ´ Mettre en place la base de donnees commands.sql sous MySQL : • nom de la base : commands • identifiant de connexion : commuser • mot de passe : commpass 21 / 58
  • 22. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME Mapping Objet / Relationnel Mise en correspondance objet / tuple ´ ´ realisee au travers d’un fichier de description des tables ´ ´ ` ´ nomme mapping.xml place a la racine du projet. On decrit le ´ nom de la table et le nom de la classe associee : • table : nom de la table • class : nom de la classe • prefix : prefixe du nom de table ´ 22 / 58
  • 23. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME Mapping Objet / Relationnel Mise en correspondance relation / attribut ´ on decrit ensuite les relations : • type : type de relation (one-to-one, one-to-many) • attribute : nom de l’attribut • class : nom de la classe associee ´ • crud : liste des operations a effectuer ´ ` (create,retrieve*,update,delete) (*) en cascade 23 / 58
  • 24. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME DTD du Mapping DTD Mapping Objet / Relationnel 1 2 3 4 5 6 7 8 9 10 11 12 <?xml version="1.0" encoding="utf-8" ?> <!ELEMENT mappings (mapping+) > <!ELEMENT mapping (relation*) > <!ATTLIST mapping table CDATA #REQUIRED > <!ATTLIST mapping class CDATA #REQUIRED > <!ATTLIST mapping prefix CDATA #REQUIRED > <!ELEMENT relation EMPTY > <!ATTLIST relation type CDATA #REQUIRED > <!ATTLIST relation attribute CDATA #REQUIRED > <!ATTLIST relation class CDATA #REQUIRED > <!ATTLIST relation crud CDATA #REQUIRED > 24 / 58
  • 25. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME Exemple Customer, Command, Product 25 / 58
  • 26. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME Mapping Mapping Objet / Relationnel 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mappings SYSTEM "mappings.dtd"> <mappings> <mapping table="command" class="Command" prefix="co"> <relation type="one-to-one" attribute="customer" class="Customer"' crud="retrieve" /> <relation type="one-to-many" attribute="commprods" class="Commprod"' crud="create,retrieve*,update,delete" /> </mapping> <mapping table="customer" class="Customer" prefix="cu"> <relation type="one-to-many" attribute="commands" class="Command"' crud="retrieve" /> </mapping> <mapping table="commprod" class="Commprod" prefix="cp"> <relation type="one-to-one" attribute="product" class="Product"' crud="retrieve" /> </mapping> <mapping table="product" class="Product" prefix="pr" /> </mappings> 26 / 58
  • 27. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME ` ´ ´ ´ Modele objet genere La classe Command 1 public class Command extends PersistentObject 2 implements PersistentInterface { 3 protected int id; 4 5 protected String date; 6 protected int cuId; 7 protected float totalPrice; 8 protected int nbCmdlines; 9 // relational fields 10 protected Customer customer; 11 protected List<Commprod> commprods; 12 } 27 / 58
  • 28. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME ` ´ ´ ´ Modele objet genere La classe Customer 1 public class Customer extends PersistentObject 2 implements PersistentInterface { 3 protected int id; 4 5 protected String firstName; 6 protected String lastName; 7 protected String email; 8 protected String password; 9 protected int rights; 10 // relational fields 11 protected List<Command> commands; 12 } 28 / 58
  • 29. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME Persistance Mise en place de la persistance 29 / 58
  • 30. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME Persistance Mise en place de la persistance 30 / 58
  • 31. ´ Developpement Web - Object Relational Mapping and Hibernate JOBYME Utilisation de JOBYME Utiliser JOBYME ´ dans le repertoire du projet lancer : ant • compile le generateur ´ ´ • genere les classes a partir du fichier de mapping ´ ´ ` • lance un test sommaire 31 / 58
  • 32. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Hibernate Hibernate 32 / 58
  • 33. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Hibernate Hibernate • framework ORM pour Java (BD Relationnelles et Objet) • requetes pour CRUD (HQL Hibernate Query Language) ˆ • utilisation des POJOs (Plain Old Java Objects) • configuration au travers de fichiers XML ou d’annotations • tres fortement configurable ` • tres difficile a maˆtriser ! ` ` ı 33 / 58
  • 34. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Historique Hibernate • 2001 par Gavin King, alternative a EJB2 ` • 2003 version 2 qui devient un standard incontournable • integration JBOSS (RedHat) ´ • 2010 version 3 : annotations 34 / 58
  • 35. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Mapping Hibernate Utilisation des mappings • par convention l’extension est .hbm.xml • on definit un fichier par classe / table ´ • placer le fichier de mapping dans le meme repertoire que ˆ ´ le fichier de classe 35 / 58
  • 36. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Mapping Hibernate fichier Mapping NomClasse.hbm.xml • permet de faire le lien entre les champs de la table et ceux de la classe • doit etre declare dans le repertoire de la classe ˆ ´ ´ ´ example Product ´ ´ Product.hbm.xml declare dans com.mysite.model 36 / 58
  • 37. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Mapping Hibernate ` ´ Modele de declaration 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.commands.model"> <class name="Product" table="product"> <id name="id" type="integer" column="pr id"> <generator class="native"/> </id> <property name="label" column="pr label"/> <property name="stock" type="int" column="pr stock"/> <property name="price" type="float" column="pr price"/> </class> </hibernate-mapping> 37 / 58
  • 38. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Mapping Hibernate Structure du mapping 1 2 3 4 5 6 7 8 9 10 11 12 13 <hibernate-mapping package="PackageName"> <class name="ClassName" table="tableName" lazy="true|false" polymorphism="implicit|explicit" where="arbitrary sql where condition" rowid="rowid" subselect="SQL expression" ... > ... </hibernate-mapping> 38 / 58
  • 39. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Mapping Hibernate Structure du Mapping • PackageName : nom du package ou se trouve la classe • ClassName : nom de la classe Java • tableName : nom de la table de la base de donnees ´ • autres parametres a definir selon la base de donnees et ` ` ´ ´ l’environnement 39 / 58
  • 40. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Mapping Hibernate ´ Definition des champs de la table • id : permet de definir l’identifiant de la table ´ • property : champ simple • composite-id : cle composee ´ ´ • timestamp : champ de type date/heure 40 / 58
  • 41. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Mapping Hibernate Structure d’un identifiant 1 <id 2 3 4 5 6 7 8 9 10 </id> 11 name="propertyName" type="typename" column="column name" unsaved-value="null|any|none|undefined|id value" access="field|property|ClassName"> node="element-name|@attribute-name|element/@attribute|." <generator class="generatorClass"/> 41 / 58
  • 42. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Mapping Hibernate ´ Definition d’un identifiant • name : nom du champ de la classe • type : integer, long, float, string, character, timestamp, binary, ... • column : nom du champ dans la table • generator : methode de generation de l’identifiant ´ ´ ´ 42 / 58
  • 43. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Mapping Hibernate ´ ´ ´ Methode de generation d’un identifiant • assigned : l’utilisateur est responsable de la generation ´ ´ • native : la base de donnees est responsable de la ´ ´ ´ generation 43 / 58
  • 44. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Mapping Hibernate ´ ´ Structure d’une propriete 1 <property 2 name="propertyName" 3 column="column name" 4 type="typename" 5 update="true|false" 6 insert="true|false" 7 formula="arbitrary SQL expression" 8 access="field|property|ClassName" 9 lazy="true|false" 10 unique="true|false" 11 not-null="true|false" 12 index="index name" 13 unique key="unique key id" 14 length="L" 15 precision="P" 16 scale="S" 17 /> 44 / 58
  • 45. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Mapping Hibernate ´ ´ ´ Definition d’une propriete • name, type, column • update, insert : indique que le champ doit etre ajoute lors ˆ ´ ´ ` d’une modification ou insertion (defaut a vrai) • formula : expression SQL qui permet de definir le champ ´ • lazy : acces aux objets associes ` ´ 45 / 58
  • 46. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate ´ Strategies de chargement Fetching • concerne le chargement des objets lies par des relations ´ • probleme complexe pour assurer l’efficacite ` ´ Exemple : chargement d’un client Faut-il charger toutes les commandes lors du chargement du client ? 46 / 58
  • 47. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate ´ Strategies de chargement Fetching strategies ´ ´ Hibernate definit 4 strategies de chargement • Immediate • Lazy : ne charge pas tout • Eager : on specifie quels objets doivent etre charges ´ ˆ ´ • Batch 47 / 58
  • 48. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Utiliser Hibernate Utilisation de Hibernate • definir un fichier de configuration ´ • demarrer Hibernate requiert la creation d’une ´ ´ SessionFactory 48 / 58
  • 49. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Fichier de configuration Fichier de configuration hibernate.cfg.xml • definit les parametres d’acces a la base de donnees ´ ` ` ` ´ • definit ou trouver les fichiers de mapping (ressource) ´ ` • doit etre place dans le repertoire src du projet ˆ ´ ´ 49 / 58
  • 50. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Configuration d’Hibernate Fichier de configuration hibernate.cfg.xml 1 <hibernate-configuration> 2 <session-factory> 3 <!-- Database connection settings --> 4 <property name="connection.driver class">com.mysql.jdbc.Driver<' 5 /property> 6 <property name="connection.url">jdbc:mysql://localhost:3306/commands<' 7 /property> 8 <property name="connection.username">commuser</property> 9 <property name="connection.password">commpass</property> 10 <!-- JDBC connection pool (use the built-in) --> 11 <property name="connection.pool size">1</property> 12 <!-- SQL dialect --> 13 <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 14 <!-- Enable Hibernate’s automatic session context management --> 15 <property name="current session context class">thread</property> 16 <!-- Disable the second-level cache --> 17 <property name="cache.provider class">org.hibernate.cache.' 18 NoCacheProvider</property> 19 <!-- Echo all executed SQL to stdout --> 20 <property name="show sql">true</property> 21 <mapping resource="com/mysite/model/command.hbm.xml"/> 22 </session-factory> 23 </hibernate-configuration> 24 25 50 / 58
  • 51. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate SessionFactory classe HibernateUtil • obtenir une instance de SessionFactory • realise l’initialisation de la connexion ´ 51 / 58
  • 52. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate HibernateUtil HibernateUtil.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import static java.lang.System.err; public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { // Create the SessionFactory from hibernate.cfg.xml sessionFactory = new Configuration().configure().buildSessionFactory()' ; } catch (Exception ex) { // Make sure you log the exception, as it might be swallowed err.println("Initial SessionFactory creation failed." + ex.getMessage(' )); throw new ExceptionInInitializerError(ex.getMessage()); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } 52 / 58
  • 53. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Librairies .jar Librairies Hibernate ´ Mettre dans le repertoire WEB-INF/lib ou lib : • l’ensemble des fichiers de Hibernate lib/required • ajouter egalement slf4j-simple ´ http://www.slf4j.org/ 53 / 58
  • 54. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate HibernateUtil Application ´ Mettre en place la configuration JAVA pour realiser un test avec Hibernate 54 / 58
  • 55. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Hibernate et annotations Annotations ` ´ Hibernate integre un mecanisme d’annotation qui permet de remplacer les fichiers de mapping par des commentaires dans le code. L’objectif est de • ne pas separer le code Java du fichier de mapping ´ • de maniere a configurer Hibernate automatiquement ` ` 55 / 58
  • 56. ´ Developpement Web - Object Relational Mapping and Hibernate Hibernate Exemple d’annotations Annotations 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import org.hibernate.annotations.Index; @Entity @Table(name="ARTIST") @NamedQueries({ @NamesQuery(name="com.oreilly.hh.artistByName", query="from Artist as artist where upper(artist.name)=upper(:name)") }) public class Artist { @Id @Column(name="ARTIST ID") @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; @Column(name="NAME",nullable=false,unique=true) @Index(name="ARTIST NAME",columnNames={"NAME"}) private String name; @ManyToMany @JoinTable(name="TRACK ARTISTS", joinColumns={@JoinColumn(name="TRACK ID")}, inverseJoinColumns={@JoinColumn(name="ARTIST ID")}) private Set<Track> tracks; } 56 / 58
  • 57. ´ Developpement Web - Object Relational Mapping and Hibernate Bibliographie Bibliographie Bibliographie 57 / 58
  • 58. ´ Developpement Web - Object Relational Mapping and Hibernate Bibliographie Bibliographie, sitographie • Hibernate Quickly, Patrick Peak, Nick Heudecker, Manning, 2006 • Hibernate in Action, Christian Bauer, Gavin King, Manning, 2005 • Harnessing Hibernate, James Elliot, Tim O’Brien, Ryan Fowler, O’Reilly, 2008 • www.hibernate.org 58 / 58