Download Hibernate

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Composants & Services Logiciels
Software Components & Services
Hibernate
These slides and case studies can be downloaded from: www.FranckBarbier.com/Enseignement
© [email protected] - Last update: Wednesday, 24 May 2017
1
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Hibernate
Hibernate is the most popular persistence framework in the Java
world (NHibernate in the .NET world)
It is an open source product which can be downloaded from:
www.hibernate.org
Hibernate Core is composed of the key libraries (.jar files)
Hibernate EntityManager is the support for Java Persistence API
(JPA)
Hibernate is the default support for JPA in JBoss while TopLink is
the default in GlassFish
Hibernate eases the development of database-oriented applications
(compared to JDBC for example)
Hibernate promotes object-orientation (polymorphism, OO
requests through HQL…) and removes the direct non-evolutive
codification of SQL inside the Java code (compared to JDBC)
© [email protected] - Last update: Wednesday, 24 May 2017
2
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Case study (UML model)
© [email protected] - Last update: Wednesday, 24 May 2017
3
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Case study (database schema)
© [email protected] - Last update: Wednesday, 24 May 2017
4
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Case study (persistent object dependencies)
© [email protected] - Last update: Wednesday, 24 May 2017
5
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Hibernate configuration
The hibernate.cfg.xml file defines the main properties of the
application. It is usually installed in the Java default
package
This file is loaded and interpreted through an instance of
the org.hibernate.cfg.Configuration class
The key notion behind Hibernate is the notions of session
factory and session:
private org.hibernate.SessionFactory _session_factory = new
org.hibernate.cfg.Configuration().configure().buildSessionFa
ctory();
private org.hibernate.Session getSession() {
return _session_factory.getCurrentSession();
}
© [email protected] - Last update: Wednesday, 24 May 2017
6
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Example of a hibernate.cfg.xml file
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
<property
name="connection.url">jdbc:derby://localhost:1527/Prison_de_Nantes</property>
<property name="connection.username">barbier</property>
<property name="connection.password">lena150496</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.DerbyDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/FranckBarbier/Java/_Prison_de_Nantes/Detenu.hbm.xml"/>
<mapping resource="com/FranckBarbier/Java/_Prison_de_Nantes/Affaire.hbm.xml"/>
<mapping resource="com/FranckBarbier/Java/_Prison_de_Nantes/Motif.hbm.xml"/>
<mapping
resource="com/FranckBarbier/Java/_Prison_de_Nantes/Incarceration.hbm.xml"/>
<mapping resource="com/FranckBarbier/Java/_Prison_de_Nantes/Decision.hbm.xml"/>
</session-factory>
</hibernate-configuration>
© [email protected] - Last update: Wednesday, 24 May 2017
7
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
The notion of session
Sessions are spaces in which objects get Hibernateoriented states
An object is included in a session as follows:
getSession().persist(_detenu);
When attached (Persistent state), an object is synchronized
with the database. All modifications on this object will
lead to appropriate modifications in the database
When flushed (or closed), all objects in a session lose their
Persistent state to recover a Transient state.
Sessions are manually or automatically associated with
database transactions
© [email protected] - Last update: Wednesday, 24 May 2017
8
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Session-oriented actions
find (or get, or load) -> it leads to the Persistent state and to a
SELECT statement, for example:
return (Detenu) session.load(Detenu.class,
primary_key);
persist (or save) -> it leads to an INSERT statement at
flush/commit time
merge (or update) -> it leads to an UPDATE statement
evict -> it leads to the Detached state
delete -> it leads to a DELETE statement
refresh -> it leads to a SELECT statement
© [email protected] - Last update: Wednesday, 24 May 2017
9
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Persistent objects
A Hibernate persistent object (a.k.a. Plain Old Java Object
or POJO) is a Java class whose instances are supposed to
persist in a database
A POJO is ruled by constraints: constructor without
arguments, normalized getter and setter methods for
persistent attributes, no use of the final Java modifier for
classes, methods and attributes…
A POJO implements the java.io.Serializable Java interface
A class playing the role of primary composite key must
also be subject to the above constraints
© [email protected] - Last update: Wednesday, 24 May 2017
10
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Persistent object lifecycle
Note: the Transient state is realized through the value
of the unsaved-value attribute
© [email protected] - Last update: Wednesday, 24 May 2017
11
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Configuring persistent objects
The mapping between database elements (tables) and
persistent objects are described in XML files, for instance:
Detenu.hbm.xml
Persistent fields are associated with table columns, for
instance:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate
Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernatemapping-3.0.dtd">
<hibernate-mapping>
<class name="com.FranckBarbier.Java._Prison_de_Nantes.Detenu"
table="DETENU">
…
…
<property
<property
<property
<property
column="PRENOM" name="_prenom" type="string"/>
column="NOM" name="_nom" type="string"/>
column="DATE_NAISSANCE" name="_date_naissance" type="date"/>
column="LIEU_NAISSANCE" name="_lieu_naissance" type="string"/>
© [email protected] - Last update: Wednesday, 24 May 2017
12
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Mapping several tables in a persistent object
Example: incorporating the DETENU and
INCARCERATION tables into the Detenu POJO:
<join optional="false"
table="INCARCERATION">
<key column="N_ECROU"/>
<property column="DATE_INCARCERATION"
name="_date_incarceration" type="date"/>
</join>
The mark optional="true" is based on the fact that one may
have "missing" rows in the INCARCERATION table
© [email protected] - Last update: Wednesday, 24 May 2017
13
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Setting up business identifiers
Hibernate does not support so well business primary keys.
However, one may have:
<hibernate-mapping>
<class
name="com.FranckBarbier.Java._Prison_de_N
antes.Detenu" table="DETENU">
<id column="N_ECROU" name="_n_ecrou">
<generator class="assigned"/>
</id>
…
© [email protected] - Last update: Wednesday, 24 May 2017
14
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Overriding equals and hashCode
public class Detenu implements java.io.Serializable {
private String _n_ecrou;
public String get_n_ecrou() {
return _n_ecrou;
}
public void set_n_ecrou(String n_ecrou) {
}
_n_ecrou = n_ecrou;
… // other persistent fields here
@Override
public boolean equals(Object object) {
if (!(object instanceof Detenu)) {
return false;
}
Detenu other = (Detenu) object;
if (_n_ecrou != other._n_ecrou && (_n_ecrou == null || !_n_ecrou.equals(other._n_ecrou))) {
return false;
}
return true;
}
@Override
public int hashCode() {
}
return _n_ecrou != null ? _n_ecrou.hashCode() : 0;
… // associations here
© [email protected] - Last update: Wednesday, 24 May 2017
15
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Setting up composite identifiers
Hibernate does not also support so well composite
(business) primary keys, for instance:
<hibernate-mapping>
<class
name="com.FranckBarbier.Java._Prison_de_Nantes.
Affaire" table="AFFAIRE">
<composite-id
class="com.FranckBarbier.Java._Prison_de_Nantes.
AffairePK" name="_primary_key">
<key-property column="N_AFFAIRE" name="_n_affaire"
type="string"/>
<key-property column="NOM_JURIDICTION"
name="_nom_juridiction" type="string"/>
</composite-id>
…
As shown here, composite primary keys require dedicated
classes, e.g., AffairePK
© [email protected] - Last update: Wednesday, 24 May 2017
16
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Setting up technical (surrogate) identifiers
Example:
<hibernate-mapping>
<class
name="com.FranckBarbier.Java._Prison_de
_Nantes.Detenu" table="DETENU">
<id column="ID_DETENU" name="_id_detenu">
<generator class="native"/>
</id>
…
© [email protected] - Last update: Wednesday, 24 May 2017
17
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
DBMS-oriented identifier generation
Example:
<hibernate-mapping>
<class
name="com.FranckBarbier.Java._Prison_de_Nantes.
Detenu" table="DETENU">
<id column="ID_DETENU" name="_id_detenu">
<generator class="sequence">
<param name="sequence">my_generator</param>
</generator>
</id>
…
Creating sequences in Oracle: CREATE SEQUENCE my_generator;
© [email protected] - Last update: Wednesday, 24 May 2017
18
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Other modes for managing identifiers
Example:
<id column="ID_DETENU" name="_id_detenu"
type="Long" unsaved-value="null">
<generator class="increment"/>
</id>
Note: the unsaved-value attribute is set to undefined when
identifiers are assigned by users (business primary keys)
Other modes: uuid.hex or uuid.string (uses IP addresses to
compute identifiers), foreign…
© [email protected] - Last update: Wednesday, 24 May 2017
19
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
One-to-one associations
An incarceration is concerned with one and only one
prisoner (and vice-versa):
<one-to-one name="_detenu" constrained="false"/>
constrained="true" is used when there is a foreign key
between the two tables
The foreign key of the Incarceration persistent object may
be constrained by that of the Detenu persistent object:
<id column="N_ECROU" name="_n_ecrou">
<generator class="foreign">
<param name="property">_detenu</param>
</generator>
</id>
© [email protected] - Last update: Wednesday, 24 May 2017
20
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Many-to-many associations
Example (Detenu.hbm.xml file):
<bag name="_toutes" table="DETENU_AFFAIRE">
<key column="N_ECROU"/>
<many-to-many
class="com.FranckBarbier.Java._Prison_de_Nantes.Affaire">
<column name="N_AFFAIRE"/>
<column name="NOM_JURIDICTION"/>
</many-to-many>
</bag>
An extract from the Detenu class is as follows:
private java.util.Collection<Affaire> _toutes;
public java.util.Collection<Affaire> get_toutes() {
return _toutes;
}
public void set_toutes(java.util.Collection<Affaire>
toutes) {
}
_toutes = toutes;
© [email protected] - Last update: Wednesday, 24 May 2017
21
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Bidirectionality
Example (Affaire.hbm.xml file):
<set inverse="true" name="_participants" table="DETENU_AFFAIRE">
<key>
<column name="N_AFFAIRE"/>
<column name="NOM_JURIDICTION"/>
</key>
<many-to-many
class="com.FranckBarbier.Java._Prison_de_Nantes.Detenu"
column="N_ECROU"/>
</set>
An extract from the Affaire class is as follows:
private java.util.Collection<Detenu> _participants;
public java.util.Collection<Detenu> get_participants() {
return _participants;
}
public void set_participants(java.util.Collection<Detenu> participants)
{
_participants = participants;
}
© [email protected] - Last update: Wednesday, 24 May 2017
22
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Bidirectionality consistency
The inverse="true" mark in Affaire.hbm.xml forces Hibernate
to maintain the DETENU_AFFAIRE table from the
Detenu persistent object
As a result, the following code is required (Affaire class):
public void addTo_participants(Detenu detenu) {
get_participants().add(detenu);
detenu.get_toutes().add(this);
}
public void removeFrom_participants(Detenu detenu) {
get_participants().remove(detenu);
detenu.get_toutes().remove(this);
}
© [email protected] - Last update: Wednesday, 24 May 2017
23
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
One-to-many associations
Example (Detenu.hbm.xml file):
<list name="_condamnation" table="CONDAMNATION"
lazy="false">
<key column="N_ECROU"/>
<list-index column="N_TYPE_DECISION"/>
<one-to-many
class="com.FranckBarbier.Java._Prison_de_Nantes.Conda
mnation"/>
</list>
An extract from the Detenu class is as follows:
private java.util.Collection<Condamnation> _condamnation;
public java.util.Collection<Condamnation>
get_condamnation() {
return _condamnation;
}
public void
set_condamnation(java.util.Collection<Condamnation>
condamnation) {
_condamnation = condamnation;
}
© [email protected] - Last update: Wednesday, 24 May 2017
24
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Many-to-one associations
Example (Incarceration.hbm.xml file):
<many-to-one column="N_MOTIF" name="_motif"
not-null="true"/>
<many-to-one name="_principale" notnull="true">
<column name="N_AFFAIRE"/>
<column name="NOM_JURIDICTION"/>
</many-to-one>
The not-null="true" mark forces Hibernate to respect the
1..* multiplicity compared to the 0..* multiplicity
© [email protected] - Last update: Wednesday, 24 May 2017
25
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Lazy loading (1/2)
Given a persistent object, a question is about the access to its linked (also
persistent) objects. For instance, given d an instance of Detenu, one may want to
access to its criminal cases:
java.util.Collection<Affaire> all = d.get_toutes();
An extract of the mapping file is as follows:
<set name="_toutes" table="DETENU_AFFAIRE" lazy="true"
fetch="select"> <!--default values-->
<key column="N_ECROU"/>
<many-to-many
class="com.FranckBarbier.Java._Prison_de_Nantes.Affai
re">
<column name="N_AFFAIRE"/>
<column name="NOM_JURIDICTION"/>
</many-to-many>
</set>
© [email protected] - Last update: Wednesday, 24 May 2017
26
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Lazy loading (2/2)
By default, dependent objects are not loaded (when an object is
itself loaded, d below) and thus becomes persistent. As a result,
Hibernate executes a deferred SELECT request when one accesses
the criminal cases of a prisoner:
java.util.Collection<Affaire> all = d.get_toutes();
The way by which lazy loading may be inhibited, relies on the lazy
and/or fetch parameter as follows:
<set name="_toutes" table="DETENU_AFFAIRE"
lazy="false"
<key column="N_ECROU"/>
<many-to-many
class="com.FranckBarbier.Java._Prison_de_Nantes.Affai
re">
<column name="N_AFFAIRE"/>
<column name="NOM_JURIDICTION"/>
</many-to-many>
</set>
Note: fetch="join" (left outer join) prevails on lazy
© [email protected] - Last update: Wednesday, 24 May 2017
27
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Cascading actions
Insertions, deletions… may be cascaded from a persistent
object to its dependent objects:
<bag name="_decision" table="DECISION"
cascade="all">
<key column="N_ECROU"/>
<one-to-many
class="com.FranckBarbier.Java._Prison_de_Nantes
.Decision"/>
</bag>
Values save-update, persist, merge, delete, lock, evict and replicate
are for one-to-one, many-to-one tags (outside collections)
Values for collections are: save-update, persist, merge, delete,
delete-orphan, lock, evict, replicate and all-delete-orphan
© [email protected] - Last update: Wednesday, 24 May 2017
28
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Inheritance
Hibernate supports three main modes for managing
inheritance relationships (and thus polymorphism):
1. A column in the table corresponding to the root class
plays the role of discriminator. There are no tables for
the subclasses
2. Subclasses have corresponding tables and a foreign key
on their ancestor table
3. No need of a table exists for the root class
© [email protected] - Last update: Wednesday, 24 May 2017
29
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Inheritance, no tables for subclasses
Example (Decision.hbm.xml):
<discriminator column="N_TYPE_DECISION" type="string" insert="false"/>
<subclass name="com.FranckBarbier.Java._Prison_de_Nantes.Condamnation"
discriminator-value="1">
<property name="_duree" column="DUREE" type="integer"/>
</subclass>
<subclass
name="com.FranckBarbier.Java._Prison_de_Nantes.Reduction_peine"
discriminator-value="2">
<property name="_duree" column="DUREE" type="integer"/>
</subclass>
<subclass
name="com.FranckBarbier.Java._Prison_de_Nantes.Liberation_definitive
" discriminator-value="3">
<property name="_date_liberation" column= "DATE_LIBERATION" type="date"/>
</subclass>
Disadvantages: some data in the DECISION table are
with null values for specialized attributes, e.g., _duree
© [email protected] - Last update: Wednesday, 24 May 2017
30
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Inheritance, tables for all classes
<joined-subclass
name="com.FranckBarbier.Java._Prison_de_Nantes.Condamnation"
table="CONDAMNATION">
<key>
<column name="N_TYPE_DECISION"/>
<column name="N_ECROU"/>
<column name="DATE_DECISION"/>
</key>
<property name="_duree" column="DUREE" type="integer"/>
</joined-subclass>
<joined-subclass
name="com.FranckBarbier.Java._Prison_de_Nantes.Reduction_peine"
table="Reduction_peine">
<key>
<column name="N_TYPE_DECISION"/>
<column name="N_ECROU"/>
<column name="DATE_DECISION"/>
</key>
<property name="_duree" column="DUREE" type="integer"/>
</joined-subclass>
<joined-subclass
name="com.FranckBarbier.Java._Prison_de_Nantes.Liberation_definitive"
table="Liberation_definitive">
<key>
<column name="N_TYPE_DECISION"/>
<column name="N_ECROU"/>
<column name="DATE_DECISION"/>
</key>
<property name="_date_liberation" column= "DATE_LIBERATION" type="date"/>
</joined-subclass>
© [email protected] - Last update: Wednesday, 24 May 2017
31
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
No table need for the root class
<union-subclass
name="com.FranckBarbier.Java._Prison_de_Nantes.Condamnatio
n" table="CONDAMNATION">
<property column="DUREE" name="_duree" type="integer"/>
</union-subclass>
<union-subclass
name="com.FranckBarbier.Java._Prison_de_Nantes.Reduction_p
eine" table="REDUCTION_PEINE">
<property column="DUREE" name="_duree" type="integer"/>
</union-subclass>
<union-subclass
name="com.FranckBarbier.Java._Prison_de_Nantes.Liberation_
definitive" table="LIBERATION_DEFINITIVE">
<property column="DATE_LIBERATION" name="_date_liberation"
type="date"/>
</union-subclass>
© [email protected] - Last update: Wednesday, 24 May 2017
32
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Sessions and transactions
Hibernate supports a home-made transaction
management mode:
org.hibernate.Session session =
_session_factory.openSession();
org.hibernate.Transaction utx =
session.beginTransaction();
…
utx.commit(); // or utx.rollback();
JTA-oriented transactions:
private javax.transaction.UserTransaction _utx;
…
org.hibernate.Session session =
session_factory.getCurrentSession();
_utx.begin();
…
_utx.commit(); // or _utx.rollback();
© [email protected] - Last update: Wednesday, 24 May 2017
33
Master « Technologies de l’Internet » - UPPA
1ère année
Programmation des Applications Internet
Internet Application Programming
Working with JTA
<property
name="hibernate.transaction.manager_lookup_c
lass">org.hibernate.transaction.SunONETransa
ctionManagerLookup</property> <!--GlassFish
support-->
<property
name="hibernate.transaction.factory_class">o
rg.hibernate.transaction.JTATransactionFacto
ry</property>
<property
name="hibernate.current_session_context_clas
s">jta</property>
© [email protected] - Last update: Wednesday, 24 May 2017
34