11 Préface Working with object-oriented software and a relational database can be cumbersome and time consuming in today's enterprise environments. Hibernate is an Object/Relational Mapping tool for Java environments. The term Object/Relational Mapping (ORM) refers to the technique of mapping a data representation from an object model to a relational data model with a SQL-based schema. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities. It can also significantly reduce development time otherwise spent with manual data handling in SQL and JDBC. Hibernate's goal is to relieve the developer from 95 percent of common data persistence related programming tasks. Hibernate may not be the best solution for data-centric applications that only use stored-procedures to implement the business logic in the database, it is most useful with object-oriented domain models and business logic in the Java-based middle-tier. However, Hibernate can certainly help you to remove or encapsulate vendor-specific SQL code and will help with the common task of result set translation from a tabular representation to a graph of objects. Si vous êtes nouveau dans Hibernate et le mapping Objet/Relationnel voire même en Java, suivez ces quelques étapes : 1. Lisez Chapitre 1, Tutorial pour un didacticiel plus long avec plus d'instructions étape par étape. 2. Lisez Chapitre 2, Architecture pour comprendre les environnements dans lesquels Hibernate peut être utilisé. 3. View the eg/ directory in the Hibernate distribution. It contains a simple standalone application. Copy your JDBC driver to the lib/ directory and edit etc/hibernate.properties, specifying correct values for your database. From a command prompt in the distribution directory, type ant eg (using Ant), or under Windows, type build eg. 4. Use this reference documentation as your primary source of information. Consider reading [JPwH] if you need more help with application design, or if you prefer a step-by-step tutorial. Also visit and download the example application from [JPwH]. 5. Les questions les plus fréquemment posées (FAQs) trouvent leur réponse sur le site web Hibernate. 6. Links to third party demos, examples, and tutorials are maintained on the Hibernate website. 7. La zone communautaire (Community Area) du site web Hibernate est une bonne source d'information sur les design patterns et sur différentes solutions d'intégration d'hibernate (Tomcat, JBoss, Spring Framework, Struts, EJB, etc). If you have questions, use the user forum linked on the Hibernate website. We also provide a JIRA issue tracking system for bug reports and feature requests. If you are interested in the xi

13 Chapitre 1. Tutorial Intended for new users, this chapter provides an step-by-step introduction to Hibernate, starting with a simple application using an in-memory database. The tutorial is based on an earlier tutorial developed by Michael Gloegl. All code is contained in the tutorials/web directory of the project source. Important This tutorial expects the user have knowledge of both Java and SQL. If you have a limited knowledge of JAVA or SQL, it is advised that you start with a good introduction to that technology prior to attempting to learn Hibernate. Note The distribution contains another example application under the tutorial/eg project source directory Partie 1 - Première application Hibernate For this example, we will set up a small database application that can store events we want to attend and information about the host(s) of these events. Note Although you can use whatever database you feel comfortable using, we will use HSQLDB [http://hsqldb.org/] (an in-memory, Java database) to avoid describing installation/setup of any particular database servers Setup The first thing we need to do is to set up the development environment. We will be using the "standard layout" advocated by alot of build tools such as Maven [http://maven.org]. Maven, in particular, has a good resource describing this layout [http://maven.apache.org/guides/ introduction/introduction-to-the-standard-directory-layout.html]. As this tutorial is to be a web application, we will be creating and making use of src/main/java, src/main/resources and src/main/webapp directories. We will be using Maven in this tutorial, taking advantage of its transitive dependency management capabilities as well as the ability of many IDEs to automatically set up a project for us based on the maven descriptor. 1

15 La première classe Astuce It is not a requirement to use Maven. If you wish to use something else to build this tutoial (such as Ant), the layout will remain the same. The only change is that you will need to manually account for all the needed dependencies. If you use something like Ivy [http://ant.apache.org/ivy/] providing transitive dependency management you would still use the dependencies mentioned below. Otherwise, you'd need to grab all dependencies, both explicit and transitive, and add them to the project's classpath. If working from the Hibernate distribution bundle, this would mean hibernate3.jar, all artifacts in the lib/required directory and all files from either the lib/bytecode/cglib or lib/bytecode/javassist directory; additionally you will need both the servlet-api jar and one of the slf4j logging backends. Save this file as pom.xml in the project root directory La première classe Next, we create a class that represents the event we want to store in the database; it is a simple JavaBean class with some properties: package org.hibernate.tutorial.domain; import java.util.date; public class Event { private Long id; private String title; private Date date; public Event() { public Long getid() { return id; private void setid(long id) { this.id = id; public Date getdate() { return date; 3

16 Chapitre 1. Tutorial public void setdate(date date) { this.date = date; public String gettitle() { return title; public void settitle(string title) { this.title = title; This class uses standard JavaBean naming conventions for property getter and setter methods, as well as private visibility for the fields. Although this is the recommended design, it is not required. Hibernate can also access fields directly, the benefit of accessor methods is robustness for refactoring. The id property holds a unique identifier value for a particular event. All persistent entity classes (there are less important dependent classes as well) will need such an identifier property if we want to use the full feature set of Hibernate. In fact, most applications, especially web applications, need to distinguish objects by identifier, so you should consider this a feature rather than a limitation. However, we usually do not manipulate the identity of an object, hence the setter method should be private. Only Hibernate will assign identifiers when an object is saved. Hibernate can access public, private, and protected accessor methods, as well as public, private and protected fields directly. The choice is up to you and you can match it to fit your application design. The no-argument constructor is a requirement for all persistent classes; Hibernate has to create objects for you, using Java Reflection. The constructor can be private, however package or public visibility is required for runtime proxy generation and efficient data retrieval without bytecode instrumentation. Save this file to the src/main/java/org/hibernate/tutorial/domain directory Le fichier de mapping Hibernate a besoin de savoir comment charger et stocker des objets d'une classe persistante. C'est là qu'intervient le fichier de mapping Hibernate. Le fichier de mapping indique à Hibernate à quelle table dans la base de données il doit accéder, et quelles colonnes de cette table il devra utiliser. La structure basique de ce fichier de mapping ressemble à ça : 4

17 Le fichier de mapping <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="org.hibernate.tutorial.domain"> [...] </hibernate-mapping> Hibernate DTD is sophisticated. You can use it for auto-completion of XML mapping elements and attributes in your editor or IDE. Opening up the DTD file in your text editor is the easiest way to get an overview of all elements and attributes, and to view the defaults, as well as some comments. Hibernate will not load the DTD file from the web, but first look it up from the classpath of the application. The DTD file is included in hibernate-core.jar (it is also included in the hibernate3.jar, if using the distribution bundle). Important We will omit the DTD declaration in future examples to shorten the code. It is, of course, not optional. Between the two hibernate-mapping tags, include a class element. All persistent entity classes (again, there might be dependent classes later on, which are not first-class entities) need a mapping to a table in the SQL database: <hibernate-mapping package="org.hibernate.tutorial.domain"> <class name="event" table="events"> </class> </hibernate-mapping> So far we have told Hibernate how to persist and load object of class Event to the table EVENTS. Each instance is now represented by a row in that table. Now we can continue by mapping the unique identifier property to the tables primary key. As we do not want to care about handling this identifier, we configure Hibernate's identifier generation strategy for a surrogate primary key column: <hibernate-mapping package="org.hibernate.tutorial.domain"> 5

18 Chapitre 1. Tutorial <class name="event" table="events"> <id name="id" column="event_id"> <generator class="native"/> </id> </class> </hibernate-mapping> The id element is the declaration of the identifier property. The name="id" mapping attribute declares the name of the JavaBean property and tells Hibernate to use the getid() and setid() methods to access the property. The column attribute tells Hibernate which column of the EVENTS table holds the primary key value. The nested generator element specifies the identifier generation strategy (aka how are identifier values generated?). In this case we choose native, which offers a level of portability depending on the configured database dialect. Hibernate supports database generated, globally unique, as well as application assigned, identifiers. Identifier value generation is also one of Hibernate's many extension points and you can plugin in your own strategy. Astuce native is no longer consider the best strategy in terms of portability. for further discussion, see Section 25.4, «Identifier generation» Lastly, we need to tell Hibernate about the remaining entity class properties. By default, no properties of the class are considered persistent: <hibernate-mapping package="org.hibernate.tutorial.domain"> <class name="event" table="events"> <id name="id" column="event_id"> <generator class="native"/> </id> <property name="date" type="timestamp" column="event_date"/> <property name="title"/> </class> </hibernate-mapping> 6

19 Configuration d'hibernate Similar to the id element, the name attribute of the property element tells Hibernate which getter and setter methods to use. In this case, Hibernate will search for getdate(), setdate(), gettitle() and settitle() methods. Note Why does the date property mapping include the column attribute, but the title does not? Without the column attribute, Hibernate by default uses the property name as the column name. This works for title, however, date is a reserved keyword in most databases so you will need to map it to a different name. The title mapping also lacks a type attribute. The types declared and used in the mapping files are not Java data types; they are not SQL database types either. These types are called Hibernate mapping types, converters which can translate from Java to SQL data types and vice versa. Again, Hibernate will try to determine the correct conversion and mapping type itself if the type attribute is not present in the mapping. In some cases this automatic detection using Reflection on the Java class might not have the default you expect or need. This is the case with the date property. Hibernate cannot know if the property, which is of java.util.date, should map to a SQL date, timestamp, or time column. Full date and time information is preserved by mapping the property with a timestamp converter. Astuce Hibernate makes this mapping type determination using reflection when the mapping files are processed. This can take time and resources, so if startup performance is important you should consider explicitly defining the type to use. Save this mapping file as src/main/resources/org/hibernate/tutorial/domain/ Event.hbm.xml Configuration d'hibernate At this point, you should have the persistent class and its mapping file in place. It is now time to configure Hibernate. First let's set up HSQLDB to run in "server mode" Note We do this do that the data remains between runs. We will utilize the Maven exec plugin to launch the HSQLDB server by running: mvn exec:java -Dexec.mainClass="org.hsqldb.Server" -Dexec.args="-database.0 file:target/data/ tutorial" You will see it start up and bind to a TCP/IP socket; this is where our application will 7

20 Chapitre 1. Tutorial connect later. If you want to start with a fresh database during this tutorial, shutdown HSQLDB, delete all files in the target/data directory, and start HSQLDB again. Hibernate will be connecting to the database on behalf of your application, so it needs to know how to obtain connections. For this tutorial we will be using a standalone connection pool (as opposed to a javax.sql.datasource). Hibernate comes with support for two third-party open source JDBC connection pools: c3p0 [https://sourceforge.net/projects/c3p0] and proxool [http:// proxool.sourceforge.net/]. However, we will be using the Hibernate built-in connection pool for this tutorial. Attention The built-in Hibernate connection pool is in no way intended for production use. It lacks several features found on any decent connection pool. For Hibernate's configuration, we can use a simple hibernate.properties file, a more sophisticated hibernate.cfg.xml file, or even complete programmatic setup. Most users prefer the XML configuration file: <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">org.hsqldb.jdbcdriver</property> <property name="connection.url">jdbc:hsqldb:hsql://localhost</property> <property name="connection.username">sa</property> <property name="connection.password"></property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.hsqldialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> 8

Core Java+ J2EE+Struts+Hibernate+Spring Java technology is a portfolio of products that are based on the power of networks and the idea that the same software should run on many different kinds of systems

Every software developer deals with bugs. The really tough bugs aren t detected by the compiler. Nasty bugs manifest themselves only when executed at runtime. Here is a list of the top ten difficult and

Enterprise Application Development In Java with AJAX and ORM ACCU London March 2010 ACCU Conference April 2010 Paul Grenyer Head of Software Engineering p.grenyer@validus-ivc.co.uk http://paulgrenyer.blogspot.com

Building Web Applications, Servlets, JSP and JDBC Overview Java 2 Enterprise Edition (JEE) is a powerful platform for building web applications. The JEE platform offers all the advantages of developing

Specialized Programme on Web Application Development using Open Source Tools Objective: At the end of the course, Students will be able to: Understand various open source tools(programming tools and databases)

2008 AGI-Information Management Consultants May be used for personal purporses only or by libraries associated to dandelon.com network. JAVA ENTERPRISE IN A NUTSHELL Third Edition Jim Farley and William

CS506 Web Design and Development Solved Online Quiz No. 01 Which of the following is a general purpose container? JFrame Dialog JPanel JApplet Which of the following package needs to be import while handling

PERFORMANCE EVALUATION OF JAVA OBJECT-RELATIONAL MAPPING TOOLS by HASEEB YOUSAF (Under the Direction of John A. Miller) ABSTRACT In the modern era of enterprise Web technology, there is strong competition

Four Days Prerequisites Students should have experience designing databases and data warehouses. Knowledge of Agile design techniques is helpful. Who Should Attend This course is targeted at database designers,

Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle

An Introduction to J2EE by Mark Johnson The Java 2, Enterprise Edition (J2EE) platform has been a global market-leading enterprise platform for the past several years. But like any large technology, J2EE

Java Server Pages combined with servlets in action We want to create a small web application (library), that illustrates the usage of JavaServer Pages combined with Java Servlets. We use the JavaServer

Maven or how to automate java builds, tests and version management with open source tools Erik Putrycz Software Engineer, Apption Software erik.putrycz@gmail.com Outlook What is Maven Maven Concepts and

Exercise 2 Implementing the Shop with EJB 2.1 Overview This exercise is a hands-on exercise in Enterprise JavaBeans (EJB). The exercise is as similar as possible to the other exercises (in other technologies).

CrownPeak Java Web Hosting Version 0.20 2014 CrownPeak Technology, Inc. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical,

Performance Monitoring API for Java Enterprise Applications Purpose Perfmon4j has been successfully deployed in hundreds of production java systems over the last 5 years. It has proven to be a highly successful

INTEGRATING MICROSOFT DYNAMICS CRM WITH SIMEGO DS3 Often the most compelling way to introduce yourself to a software product is to try deliver value as soon as possible. Simego DS3 is designed to get you

Web Application Development Fall 2012 Final Exam Study Guide This guide is designed to be a list of topics that might appear on the final exam. Most (if not all) of the answers to these questions are in

Budapest University of Technology and Economics Department of Measurement and Information Systems Fault Tolerant Systems Research Group Service Integration course Cassandra Oszkár Semeráth Gábor Szárnyas

This presentation will introduce the basic concepts of the Java Persistence API by presenting several code examples. Page 1 of 14 This presentation will begin with examples of how to create and use JPA

Database Application Design and Development Virtually all real-world user interaction with databases is indirect it is mediated through an application A database application effectively adds additional

The NewSQL database you ll never outgrow Integrating with Hadoop Hadoop is an open source framework for managing and manipulating massive volumes of data. is an database for handling high velocity data.

September Case Studies of Running the Platform NetBeans UML Servlet JSP GlassFish EJB In this project we display in the browser the Hello World, Everyone! message created in the session bean with servlets

Oracle Business Intelligence Enterprise Edition (OBIEE) Training: Working with Oracle Business Intelligence Answers Introduction to Oracle BI Answers Working with requests in Oracle BI Answers Using advanced