Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Composants & Services Logiciels Software Components & Services Hibernate These slides and case studies can be downloaded from:
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année 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: 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)
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Case study (UML model)
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Case study (database schema)
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Case study (persistent object dependencies)
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année 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(); }
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Example of a hibernate.cfg.xml file <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" " org.apache.derby.jdbc.ClientDriver org.apache.derby.jdbc.ClientDriver jdbc:derby://localhost:1527/Prison_de_Nantes jdbc:derby://localhost:1527/Prison_de_Nantes barbier barbier lena lena org.hibernate.dialect.DerbyDialect org.hibernate.dialect.DerbyDialect true true </session-factory></hibernate-configuration>
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année The notion of session Sessions are spaces in which objects get Hibernate- oriented 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
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année 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
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année 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
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Persistent object lifecycle Note: the Transient state is realized through the value of the unsaved-value attribute
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année 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: … …
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Mapping several tables in a persistent object Example: incorporating the DETENU and INCARCERATION tables into the Detenu POJO: The mark optional="true" is based on the fact that one may have "missing" rows in the INCARCERATION table
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Setting up business identifiers Hibernate does not support so well business primary keys. However, one may have: …
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année 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 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; public int hashCode() { return _n_ecrou != null ? _n_ecrou.hashCode() : 0; } … // associations here
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Setting up composite identifiers Hibernate does not also support so well composite (business) primary keys, for instance: … As shown here, composite primary keys require dedicated classes, e.g., AffairePK
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Setting up technical (surrogate) identifiers Example: …
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année DBMS-oriented identifier generation Example: my_generator … Creating sequences in Oracle: CREATE SEQUENCE my_generator;
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Other modes for managing identifiers Example: 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…
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année One-to-one associations An incarceration is concerned with one and only one prisoner (and vice-versa): 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: _detenu
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Many-to-many associations Example (Detenu.hbm.xml file): An extract from the Detenu class is as follows: private java.util.Collection _toutes; public java.util.Collection get_toutes() { return _toutes; } public void set_toutes(java.util.Collection toutes) { _toutes = toutes; }
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Bidirectionality Example (Affaire.hbm.xml file): An extract from the Affaire class is as follows: private java.util.Collection _participants; public java.util.Collection get_participants() { return _participants; } public void set_participants(java.util.Collection participants) { _participants = participants; }
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année 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); }
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année One-to-many associations Example (Detenu.hbm.xml file): An extract from the Detenu class is as follows: private java.util.Collection _condamnation; public java.util.Collection get_condamnation() { return _condamnation; } public void set_condamnation(java.util.Collection condamnation) { _condamnation = condamnation; }
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Many-to-one associations Example (Incarceration.hbm.xml file): The not-null="true" mark forces Hibernate to respect the 1..* multiplicity compared to the 0..* multiplicity
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année 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 all = d.get_toutes(); An extract of the mapping file is as follows:
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année 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 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" Note: fetch="join" (left outer join) prevails on lazy
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Cascading actions Insertions, deletions… may be cascaded from a persistent object to its dependent objects: 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
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année 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
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Inheritance, no tables for subclasses Example (Decision.hbm.xml): Disadvantages: some data in the DECISION table are with null values for specialized attributes, e.g., _duree
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Inheritance, tables for all classes
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année No table need for the root class </union-subclass> </union-subclass> </union-subclass>
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année 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();
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February Master « Technologies de l’Internet » - UPPA 1ère année Working with JTA org.hibernate.transaction.SunONETransa ctionManagerLookup org.hibernate.transaction.SunONETransa ctionManagerLookup o rg.hibernate.transaction.JTATransactionFacto ry o rg.hibernate.transaction.JTATransactionFacto ry jta jta