Hibernate Tutorial

HIBERNATE TUTORIAL

Simply Easy Learning by tutorialspoint.com

tutorialspoint.com

ABOUT THE TUTORIAL

Hibernate Tutorial
Hibernate is a high-performance Object/Relational persistence and query service which is licensed under the open source GNU Lesser General Public License (LGPL) and is free to download. 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. This tutorial will teach you how to use Hibernate to develop your database based web applications in simple and easy steps.

Audience
This tutorial is designed for Java programmers with a need to understand the Hibernate framework and API. After completing this tutorial you will find yourself at a moderate level of expertise in using Hibernate from where you can take yourself to next levels.

Prerequisites
We assume you have good understanding of the Java programming language. A basic understanding of relational databases, JDBC and SQL is very helpful.

Copyright & Disclaimer Notice
 All the content
and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at webmaster@tutorialspoint.com

TUTORIALS POINT Simply Easy Learning

........................................................................................................................................................................................................................................................ 30 JDK-related types ..................................... 29 Primitive types ............................................................................................................................ 15 Transaction Object ......................................................... 10 Hibernate Overview ................................................ 16 Downloading Hibernate:........................................... 15 Hibernate Environment ...................................... 11 Supported Databases ......................................................................................................................................................................................................... 18 Hibernate Properties ....................................................................................................................................................................... 26 Hibernate Mapping Types ........................................................................... 9 Java ORM Frameworks ................................................................... 15 Criteria Object .............................. 8 Pros and Cons of JDBC ................................................................... 18 Hibernate with MySQL Database ................................................................................................................................................................................................... 2 Prerequisites .................................................................. 22 Hibernate Persistent Class ......................................................................................................... 17 Hibernate Prerequisites ....................................................................................................................................................... 2 ORM Overview.................................................................... 19 Hibernate Sessions .................................................................................................................................................................................. 14 SessionFactory Object ................................. 8 What is ORM? ... 17 Hibernate Configuration .................................................... 13 Configuration Object ............................... 11 Hibernate Advantages ................................................................ 16 Installing Hibernate ............ 24 Hibernate Mapping Files ...................................... 12 Hibernate Architecture ........................................................................ 2 Audience .......................................... 21 Session Interface Methods .......................... 12 Supported Technologies ................................................................................................................. 15 Query Object ................ 29 Date and time types ............. 14 Session Object ................................................................ 30 TUTORIALS POINT Simply Easy Learning . 24 A simple POJO example: .......................Table of Content Hibernate Tutorial .......................................... 29 Binary and large object types ................ 2 Copyright & Disclaimer Notice.................................................................. 8 Why Object Relational Mapping (ORM)? ..................................................................................

............ 47 Compilation and Execution .............................. 60 Compilation and Execution .......................................... 37 Define POJO Classes .................................................................................................................................................................................................................. 36 Collections Mappings .................................... 68 Hibernate SortedMap Mappings ......................Hibernate Examples .............. 57 Define RDBMS Tables .............. 39 Create Application Class ............................................................. 32 Create Mapping Configuration File ............... 42 Hibernate SortedSet Mappings ............................................................ 31 Create POJO Classes ................................................................................... 52 Create Application Class ........ 32 Create Application Class ................. 49 Hibernate List Mappings .............................................................. 37 Define Hibernate Mapping File ................................................................................................................................. 44 Define Hibernate Mapping File ........................................................................ 63 Define RDBMS Tables ........ 31 Create Database Tables .......................... 36 Hibernate Set Mappings ..................................................................................................... 69 TUTORIALS POINT Simply Easy Learning ..................... 58 Create Application Class ............................................... 43 Define POJO Classes ......................................................................................................................................................................................... 35 Hibernate O/R Mapping .................................. 40 Compilation and Execution ....................................................... 57 Define Hibernate Mapping File .... 62 Hibernate Map Mappings ............................................................................................................................................................................................................................................................................................................................. 57 Define POJO Classes .................................................................................................................................................... 63 Define POJO Classes ............................................................................................................................................................................................................. 65 Create Application Class ............................................. 55 Hibernate Bag Mappings .... 66 Compilation and Execution ............................................................ 50 Define POJO Classes ............................ 53 Compilation and Execution ........................................................................................ 36 Define RDBMS Tables ................................................................................. 33 Compilation and Execution .......................................................... 43 Define RDBMS Tables ............................................................................................................................................... 63 Define Hibernate Mapping File .................................................................................... 50 Define RDBMS Tables ............................................................. 45 Create Application Class ......................................................................................................................... 51 Define Hibernate Mapping File ............................................................................................

...................................................................................................................... 70 Define Hibernate Mapping File ........................................................................................ 83 Define RDBMS Tables ...................................................... 103 Define POJO Classes .................... 99 Create Application Class .......................................................... 83 Define POJO Classes ............................................................................................................................................... 112 @Table Annotation ........................................................................................................... 100 Compilation and Execution ........................................................................................................................................................................... 111 @Entity Annotation ......................... 97 Define POJO Classes ........................................................................................................................................................... 111 Annotated Class Example ................................................. 111 Environment Setup for Hibernate Annotation .................... 107 Compilation and Execution ..................................................... 76 Define POJO Classes .........................Define RDBMS Tables ............ 93 Compilation and Execution ................................... 103 Define RDBMS Tables ..................... 82 Hibernate One-to-One Mappings .................... 106 Create Application Class ..................................................................................................................................................................................................................................................... 95 Hibernate Many-to-Many Mappings ................................................................... 90 Define POJO Classes .... 89 Hibernate One-to-Many Mappings .................................................................................................................................................. 104 Define Hibernate Mapping File ................................................................................................................. 91 Define Hibernate Mapping File .................................................................................................................................................................. 79 Compilation and Execution ................................... 90 Define RDBMS Tables ............... 102 Component Mappings ......................... 113 TUTORIALS POINT Simply Easy Learning ...................................... 86 Compilation and Execution ................................................................................................................................................................................................................................. 76 Define RDBMS Tables ................................................................................................ 77 Define Hibernate Mapping File .............................................. 103 Hibernate Component Mappings.................................................................................................. 92 Create Application Class .......................................................................................... 109 Hibernate Annotations....... 75 Association Mappings .................................... 84 Define Hibernate Mapping File ........ 69 Define POJO Classes .. 71 Compilation and Execution ....................... 97 Define Hibernate Mapping File ........................... 76 Hibernate Many-to-One Mappings .............................................................................. 96 Define RDBMS Tables ..........................................................................

........................ 119 INSERT Clause ................................................................. 113 Create Application Class ...................................................................................................................................... 134 Concurrency strategies . 118 Using Named Paramters ........................................................................................... 120 Hibernate Criteria Queries ................................ 119 DELETE Clause ................................................................................................................................................................ 134 Query-level cache ..................................................... 123 Projections & Aggregations .............................................. 118 ORDER BY Clause ................ 113 Database Configuration ......... 119 Aggregate Methods ................................................................................................................................................................................................... 117 AS Clause .............................................. 128 Scalar queries ............................................................................................................................ 128 Entity queries ...................................................................... 133 First-level cache .............................................................................................................................................. 121 Restrictions with Criteria ................ 117 SELECT Clause ................. 116 Hibernate Query Language ............................................................................. 123 Criteria Queries Example ........................................................................... 119 UPDATE Clause ..... 121 Pagination using Criteria .................................................... 122 Sorting the Results ............................... 128 Named SQL queries.................................................................................................................................................................................................................. 118 WHERE Clause ........ 113 @Column Annotation ................................................... 129 Compilation and Execution ...................................................................................................... 135 The Query-level Cache ......................................................................................................................................................................................... 127 Hibernate Native SQL ......@Id and @GeneratedValue Annotations........................... 117 FROM Clause .................................. 133 Second-level cache ............................................................... 134 Cache provider ........................... 119 Pagination using Query ............................... 137 TUTORIALS POINT Simply Easy Learning .......... 118 GROUP BY Clause.................................................................................................................................................................... 132 Hibernate Caching ...................................................................................................................................................................... 115 Compilation and Execution .................... 134 The Second Level Cache ................................................................................ 123 Compilation and Execution ........................................................................................................................................................................................................................................................................................................................................................................................... 129 Native SQL Example ...............................

.......... 143 How to use Interceptors? ............................................................................................................................ 146 Compilation and Execution ................................. 144 Create Interceptors ................................. 145 Create Mapping Configuration File ...................................................................Hibernate Batch Processing ........................................................................................................................... 142 Hibernate Interceptors...................... 148 TUTORIALS POINT Simply Easy Learning ...................................................... 138 Batch Processing Example .................... 145 Create Database Tables ................................................... 144 Create POJO Classes ..................................................................................................................................................................... 139 Compilation and Execution ..................................... 146 Create Application Class .......................................

private String last_name.CHAPTER 1 ORM Overview J DBC stands for Java Database Connectivity and provides a set of Java API for accessing the relational databases from Java program. TUTORIALS POINT Simply Easy Learning . there's a mismatch between the object model and the relational database. such as Java or C# represent it as an interconnected graph of objects. JDBC provides a flexible architecture to write a database independent application that can run on different platforms and interact with different DBMS without any modification. Consider the following Java Class with proper constructors and associated public function: public class Employee { private int id. RDBMSs represent data in a tabular format whereas object-oriented languages. Pros and Cons of JDBC Pros of JDBC Cons of JDBC     Clean and simple SQL processing Good performance with large data Very good for small applications Simple syntax so easy to learn      Complex if it is used in large projects Large programming overhead No encapsulation Hard to implement MVC concept Query is DBMS specific Why Object Relational Mapping (ORM)? When we work with an object-oriented systems. These Java APIs enables Java programs to execute SQL statements and interact with any SQL compliant database. private String first_name. private int salary.

however. what if we need to modify the design of our database after having developed few pages or our application? Second. salary INT default NULL.salary = salary. int salary) { this.last_name = lname. What is ORM? ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data between relational databases and object oriented programming languages such as Java. } public int getSalary() { return salary.equals(b)).first_name = fname. An ORM system has following advantages over plain JDBC TUTORIALS POINT Simply Easy Learning . this. A RDBMS defines exactly one notion of 'sameness': the primary key. this. The Object-Relational Mapping (ORM) is the solution to handle all the above impedance mismatches. Loading and storing objects in a relational database exposes us to the following five mismatch problems.public Employee() {} public Employee(String fname. } public String getFirstName() { return first_name. String lname. The ways you access objects in Java and in a RDBMS are fundamentally different. First problem. first_name VARCHAR(20) default NULL. Object-oriented languages represent associations using object references where as am RDBMS represents an association as a foreign key column. } } Consider above objects need to be stored and retrieved into the following RDBMS table: create table EMPLOYEE ( id INT NOT NULL auto_increment. last_name VARCHAR(20) default NULL. C# etc. defines both object identity (a==b) and object equality (a. } public String getLastName() { return last_name. PRIMARY KEY (id) ). Java. RDBMSs do not define anything similar to Inheritance which is a natural paradigm in object-oriented programming languages. Mismatch Granularity Inheritance Identity Associations Navigation Description Sometimes you will have an object model which has more classes than the number of corresponding tables in the database. } public int getId() { return id.

       Enterprise JavaBeans Entity Beans Java Data Objects Castor TopLink Spring DAO Hibernate And many more TUTORIALS POINT Simply Easy Learning .S. A language or API to specify queries that refer to classes and properties of classes. Transaction management and automatic key generation.N. An ORM solution consists of the following four entities: S. Advantages 1 2 3 4 5 6 7 Lets business code access objects rather than DB tables. Solutions 1 2 3 4 An API to perform basic CRUD operations on objects of persistent classes. Based on JDBC 'under the hood' No need to deal with the database implementation. A persistent framework is an ORM service that stores and retrieves objects into a relational database. Java ORM Frameworks There are several persistent frameworks and ORM options in Java.N. A configurable facility for specifying mapping metadata. and other optimization functions. Entities based on business concepts rather than database structure. Fast development of application. lazy association fetching. Hides details of SQL queries from OO logic. A technique to interact with transactional objects to perform dirty checking.

Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects. If there is change in Database or in any table then the only need to change XML file properties.CHAPTER 2 Hibernate Overview H ibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open source persistent framework created by Gavin King in 2001. Provides simple APIs for storing and retrieving Java objects directly to and from the database. TUTORIALS POINT Simply Easy Learning . Hibernate sits between traditional Java objects and database server to handle all the work in persisting those objects based on the appropriate O/R mechanisms and patterns. Hibernate Advantages       Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code. Hibernate does not require an application server to operate. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from 95% of common data persistence related programming tasks. high performance Object-Relational Persistence and Query service for any Java Application. Manipulates Complex associations of objects of your database. It is a powerful.

         HSQL Database Engine DB2/NT MySQL PostgreSQL FrontBase Oracle Microsoft SQL Server Database Sybase SQL Server Informix Dynamic Server Supported Technologies Hibernate supports a variety of other technologies. Following is list of few of the database engines supported by Hibernate.  Minimize database access with smart fetching strategies. Supported Databases Hibernate supports almost all the major RDBMS. including the following:     XDoclet Spring J2EE Eclipse plug-ins Maven TUTORIALS POINT Simply Easy Learning . Provides Simple querying of data.

Hibernate makes use of the database and configuration data to provide persistence services (and persistent objects) to the application. Following is a very high level view of the Hibernate Application Architecture. TUTORIALS POINT Simply Easy Learning .CHAPTER 3 Hibernate Architecture T he Hibernate architecture is layered to keep you isolated from having to know the underlying APIs. Following is a detailed view of the Hibernate Application Architecture with few important core classes.

Java Transaction API(JTA). TUTORIALS POINT Simply Easy Learning . These files are hibernate. like JDBC. and Java Naming and Directory Interface (JNDI). It represents a configuration or properties file required by the Hibernate.properties and hibernate. SessionFactory Object Configuration object is used to create a SessionFactory object which inturn configures Hibernate for the application using the supplied configuration file and allows for a Session object to be instantiated.cfg. The SessionFactory is a thread safe object and used by all the threads of an application.xml. Class Mapping Setup: This component creates the connection between the Java classes and database tables. Following section gives brief description of each of the class objects involved in Hibernate Application Architecture. JDBC provides a rudimentary level of abstraction of functionality common to relational databases. JNDI and JTA allow Hibernate to be integrated with J2EE application servers. allowing almost any database with a JDBC driver to be supported by Hibernate. Configuration Object The Configuration object is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization.Hibernate uses various existing Java APIs. The Configuration object provides two keys components:   Database Connection: This is handled through one or more configuration files supported by Hibernate.

So if you are using multiple databases then you would have to create multiple SessionFactory objects. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object. Transaction Object A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. Criteria Object Criteria object are used to create and execute object oriented criteria queries to retrieve objects. Query Object Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. and finally to execute the query. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA). A Query instance is used to bind query parameters. TUTORIALS POINT Simply Easy Learning . Session Object A Session is used to get a physical connection with a database. instead managing transactions in their own application code.The SessionFactory is heavyweight object so usually it is created during application start up and kept for later use. limit the number of results returned by the query. You would need one SessionFactory object per database using a separate configuration file. This is an optional object and Hibernate applications may choose not to use this interface. The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.

hibernate.6.Final and when you unzip the downloaded file it will give you directory structure as follows.tz file for Unix. so make sure you already have setup for MySQL database. or Unix and then proceed to the next step to download . Make a choice whether you want to install Hibernate on Windows.4.org/downloads. TUTORIALS POINT Simply Easy Learning . At the time of writing this tutorial I downloaded hibernate-distribution-3. Following are the simple steps to download and install Hibernate on your machine. For a more detail on MySQL you can check our MySQL Tutorial. Download the latest version of Hibernate from http://www.zip file for windows and . We will work with MySQL database to experiment with Hibernate examples.CHAPTER 4 Hibernate Environment T    his chapter will explain how to install Hibernate and other associated packages to prepare a develop environment for the Hibernate applications. Downloading Hibernate: It is assumed that you already have latest version of Java is installed on your machine.

sourceforge.Logging Facade for Java http://www.slf4j.Appropriate changes to Java classes at runtime http://cglib.org/log4j Commons .apache.XML parsing www. This file lies in the root directory of the installation and is the primary JAR that Hibernate needs to do its work.dom4j.net/ log4j .N. S.   Now copy all the library files from /lib into your CLASSPATH. you need to perform following two simple steps. To install these packages you would have to copy library files from /lib into your CLASSPATH.XSLT Processor http://xml.apache.org/xerces-j/ cglib . Make sure you are setting your CLASSPATH variable properly otherwise you will face problem while compiling your application.org/ Xalan .org/xalan-j/ Xerces . Email etc. Packages/Libraries 1 2 3 4 5 6 7 dom4j .Logging.Installing Hibernate Once you downloaded and unzipped the latest version of the Hibernate Installation file.org TUTORIALS POINT Simply Easy Learning .org/commons SLF4J .jar file into your CLASSPATH. Hibernate Prerequisites Following is the list of the packages/libraries required by Hibernate and you should install them before starting with Hibernate. and change your CLASSPATH variable accordingly.apache.apache. and change your classpath variable to include all the JARs: Finally copy hibernate3.Logging Faremwork http://logging. http://jakarta.The Xerces Java Parser http://xml.

hibernate.connection. Hibernate Properties Following is the list of important properties you would require to configure for a databases in a standalone situation: S. hibernate. If you are using a database along with an application server and JNDI then you would have to configure the following properties: TUTORIALS POINT Simply Easy Learning .url The JDBC URL to the database instance. hibernate. Most of the properties take their default values and it is not required to specify them in the property file unless it is really required.N.username The database username.pool_size Limits the number of connections waiting in the Hibernate database connection pool. hibernate.connection.connection.connection.properties.cfg.connection.xml.cfg.CHAPTER 5 Hibernate Configuration H ibernate requires to know in advance where to find the mapping information that defines how your Java classes relate to the database tables. Hibernate also requires a set of configuration settings related to database and other related parameters. Properties and Description 1 2 3 4 5 6 7 hibernate.driver_class The JDBC driver class.xml to specify required Hibernate properties in my examples. or as an XML file named hibernate. hibernate. All such information is usually supplied as a standard Java properties file called hibernate.dialect This property makes Hibernate generate the appropriate SQL for the chosen database. I will consider XML formatted file hibernate.autocommit Allows autocommit mode to be used for the JDBC connection. hibernate.password The database password. This file is kept in the root directory of your application's classpath.connection.

hibernate. hibernate. hibernate. You would have to make sure that you have testdb database available in your MySQL database and you have a user test available to access the database.jndi.MySQLDialect </property> <property name="hibernate.username The database username.driver_class"> com.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.Driver </property> <!-.S.jndi. Let us createhibernate.jdbc.username"> root </property> <property name="hibernate.connection. hibernate.N.url Provides the URL for JNDI. <?xml version="1.0.connection.hibernate.Assume test is the database name --> <property name="hibernate.0.connection.dialect"> org.connection.hibernate.cfg.List of XML mapping files --> <mapping resource="Employee.connection.org/dtd/hibernate-configuration-3.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration SYSTEM "http://www.<JNDIpropertyname> Passes any JNDI property you like to the JNDI InitialContext.dialect. The XML configuration file must conform to the Hibernate 3 Configuration DTD.org/dtd/hibernate-configuration-3.class The InitialContext class for JNDI. hibernate.jndi. which is available from http://www.hibernate.xml"/> </session-factory> </hibernate-configuration> TUTORIALS POINT Simply Easy Learning .dtd.mysql.password The database password. Hibernate with MySQL Database MySQL is one of the most popular open-source database systems available today. Properties and Description 1 2 3 4 5 6 hibernate.datasource The JNDI name defined in the application server context you are using for the application.hbm.password"> root123 </property> <!-.url"> jdbc:mysql://localhost/test </property> <property name="hibernate.connection.connection.xml configuration file and place it in the root of your application's classpath.

IngresDialect org.dialect.dialect.dialect.hibernate.hibernate.HSQLDialect org.SAPDBDialect org.InformixDialect org.hibernate.dialect.hibernate.MySQLDialect org.hibernate.SQLServerDialect org.The above configuration file includes <mapping> tags which are related to hibernate-mapping file and we will see in next chapter what exactly is a hibernate mapping file and how and why do we use it.hibernate.dialect.hibernate.dialect.hibernate.InterbaseDialect org.dialect.Oracle10gDialect org.hibernate.SybaseDialect org.hibernate.HSQLDialect org.dialect.PostgreSQLDialect org.dialect.OracleDialect org.dialect. TUTORIALS POINT Simply Easy Learning .dialect.hibernate.dialect. A TestSuite is a Composite of Tests.hibernate.hibernate.hibernate.dialect.dialect.hibernate. Following is the list of various important databases dialect property type: Database DB2 HSQLDB HypersonicSQL Informix Ingres Interbase Microsoft SQL Server 2000 Microsoft SQL Server 2005 Microsoft SQL Server 2008 MySQL Oracle (any version) Oracle 11g Oracle 10g Oracle 9i PostgreSQL Progress SAP DB Sybase Sybase Anywhere Dialect Property org.ProgressDialect org.hibernate.SybaseAnywhereDialect Serial No 1 2 3 4 Class Name Assert TestCase TestResult TestSuite Functionality A set of assert methods.hibernate.SQLServer2008Dialect org.hibernate.dialect.DB2Dialect org.Oracle9iDialect org.Oracle10gDialect org. A test case defines the fixture to run multiple tests.dialect.dialect.hibernate.dialect.dialect. A TestResult collects the results of executing a test case.SQLServer2005Dialect org.

try { tx = session. read and delete operations for instances of mapped entity classes. A Session instance is serializable if its persistent classes are serializable. persistent: You can make a transient instance persistent by associating it with a Session. the transaction must be rolled back and the session must be discarded. A typical transaction should use the following idiom: Session session = factory. an identifier value and is associated with a Session. } catch (Exception e) { if (tx!=null) tx. Persistent objects are saved and retrieved through a Session object.rollback().close().openSession(). Transaction tx = null.printStackTrace(). A persistent instance has a representation in the database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. }finally { session. detached: Once we close the Hibernate Session.CHAPTER 6 Hibernate Sessions A    Session is used to get a physical connection with a database.. the persistent instance will become a detached instance. TUTORIALS POINT Simply Easy Learning .beginTransaction(). The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed. The main function of the Session is to offer create. e.. Instances may exist in one of the following three states at a given point in time: transient: A new instance of a a persistent class which is not associated with a Session and has no representation in the database and no identifier value is considered transient by Hibernate. // do some work . tx.commit(). } If the Session throws an exception.

for the given entity name. SQLQuery createSQLQuery(String queryString) Create a new instance of SQLQuery for the given SQL query string. String queryString) Create a new instance of Query for the given collection and filter string. for the given entity class. Serializable getIdentifier(Object object) Return the identifier value of the given entity as associated with this session. You can check Hibernate documentation for a complete list of methods associated with Session and SessionFactory. boolean isDirty() Does this session contain any changes which must be synchronized with the database? 13 14 15 16 17 18 TUTORIALS POINT Simply Easy Learning .N. Object object) Remove a persistent instance from the datastore. or null if there is no such persistent instance. Criteria createCriteria(Class persistentClass) Create a new Criteria instance. Connection close() End the session by releasing the JDBC connection and cleaning up. void cancelQuery() Cancel the execution of the current query. Query createQuery(String queryString) Create a new instance of Query for the given HQL query string. SessionFactory getSessionFactory() Get the session factory which created this session. void refresh(Object object) Re-read the state of the given instance from the underlying database. Criteria createCriteria(String entityName) Create a new Criteria instance. S. boolean isConnected() Check if the session is currently connected. void delete(Object object) Remove a persistent instance from the datastore. Session get(String entityName.Session Interface Methods There are number of methods provided by the Session interface but I'm going to list down few important methods only. Query createFilter(Object collection. Session Methods and Description 1 2 3 4 5 6 7 8 9 10 11 12 Transaction beginTransaction() Begin a unit of work and return the associated Transaction object. or a superclass of an entity class. Transaction getTransaction() Get the Transaction instance associated with this session. void clear() Completely clear the session. void delete(String entityName. Serializable id) Return the persistent instance of the given named entity with the given identifier. which we will use in this tutorial.

Serializable save(Object object) Persist the given transient instance. first assigning a generated identifier. void update(String entityName. void update(Object object) Update the persistent instance with the identifier of the given detached instance. TUTORIALS POINT Simply Easy Learning . Object object) Update the persistent instance with the identifier of the given detached instance. void saveOrUpdate(Object object) Either save(Object) or update(Object) the given instance.19 20 21 22 23 boolean isOpen() Check if the session is still open.

private String firstName. and in particular not an Enterprise JavaBean. not a special object. private int salary. All Java classes that will be persisted need a default constructor. All classes should contain an ID in order to allow easy identification of your objects within Hibernate and the database. All classes that do not extend or implement some specialized classes and interfaces required by the EJB framework. proxies. Hibernate works best if these classes follow some simple rules. This property maps to the primary key column of a database table. Java classes whose objects or instances will be stored in database tables are called persistent classes in Hibernate. There are following main rules of persistent classes. The POJO name is used to emphasize that a given object is an ordinary Java Object. private String lastName. A central feature of Hibernate. however.CHAPTER 7 Hibernate Persistent Class T      he entire concept of Hibernate is to take the values from Java class attributes and persist them to a database table. A simple POJO example: Based on the few rules mentioned above we can define a POJO class as follows: public class Employee { private int id. also known as the Plain Old Java Object (POJO) programming model. All attributes that will be persisted should be declared private and have getXXX and setXXXmethods defined in the JavaBean style. none of these rules are hard requirements. A mapping document helps Hibernate in determining how to pull the values from the classes and map them with table and associated fields. public Employee() {} TUTORIALS POINT Simply Easy Learning . depends upon the persistent class being either non-final. or the implementation of an interface that declares all public methods.

public Employee(String fname. } public void setId( int id ) { this. } public String getLastName() { return lastName.lastName = last_name.firstName = fname. int salary) { this. } public void setFirstName( String first_name ) { this.firstName = first_name. this.lastName = lname. } public int getId() { return id. this. } } TUTORIALS POINT Simply Easy Learning .id = id. String lname. } public void setLastName( String last_name ) { this. } public int getSalary() { return salary.salary = salary. } public String getFirstName() { return firstName. } public void setSalary( int salary ) { this.salary = salary.

firstName = fname. } public void setFirstName( String first_name ) { this. } public String getLastName() { return lastName. private String firstName. This mapping file instructs Hibernate how to map the defined class or classes to the database tables.lastName = lname. } public int getSalary() { return salary. String lname. These include XDoclet.firstName = first_name. public class Employee { private int id. } public void setLastName( String last_name ) { this.id = id. public Employee() {} public Employee(String fname.CHAPTER 8 Hibernate Mapping Files A n Object/relational mappings are usually defined in an XML document. a number of tools exist to generate the mapping document. Middlegen and AndroMDA for advanced Hibernate users. this. private int salary. } TUTORIALS POINT Simply Easy Learning . } public void setId( int id ) { this.lastName = last_name. } public String getFirstName() { return firstName. Though many Hibernate users choose to write the XML by hand. this. private String lastName. int salary) { this.salary = salary. Let us consider our previously defined POJO class whose objects will persist in the table defined in next section. } public int getId() { return id.

<?xml version="1. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>.org/dtd/hibernate-mapping-3. Set the class attribute of the generator element is set to native to let hibernate pick up    TUTORIALS POINT Simply Easy Learning . We saved our mapping document in the file Employee. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.0. this mapping types will convert from Java to SQL data type.xml. The <class> elements are used to define specific mappings from a Java classes to the database tables. Let us see little detail about the mapping elements used in the mapping file:   The mapping document is an XML document having <hibernate-mapping> as the root element which contains all the <class> elements.xml.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. salary INT default NULL. The <meta> element is optional element and can be used to create the class description.public void setSalary( int salary ) { this. Consider above objects need to be stored and retrieved into the following RDBMS table: create table EMPLOYEE ( id INT NOT NULL auto_increment. The type attribute holds the hibernate mapping type.hbm. Based on the two above entities we can define following mapping file which instructs Hibernate how to map the defined class or classes to the database tables. last_name VARCHAR(20) default NULL.hbm. The <id> element maps the unique ID attribute in class to the primary key of the database table.hibernate. first_name VARCHAR(20) default NULL. } } There would be one table corresponding to each object you are willing to provide persistence. PRIMARY KEY (id) ). The <generator> element within the id element is used to automatically generate the primary key values.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.salary = salary.

either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database.

The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.

There are other attributes and elements available which will be used in a mapping document and I would try to cover as many as possible while discussing other Hibernate related topics.

TUTORIALS POINT Simply Easy Learning

CHAPTER
.

9

Hibernate Mapping Types

W
integer long short float double big_decimal character string byte boolean yes/no true/false

hen you prepare a Hibernate mapping document, we have seen that you map Java data types into

RDBMS data types. 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, which can translate from Java to SQL data types and vice versa. This chapter lists down all the basic, date and time, large object, and various other built-in mapping types.

Primitive types
Mapping type Java type int or java.lang.Integer long or java.lang.Long short or java.lang.Short float or java.lang.Float double or java.lang.Double java.math.BigDecimal java.lang.String java.lang.String byte or java.lang.Byte boolean or java.lang.Boolean boolean or java.lang.Boolean boolean or java.lang.Boolean ANSI SQL Type INTEGER BIGINT SMALLINT FLOAT DOUBLE NUMERIC CHAR(1) VARCHAR TINYINT BIT CHAR(1) ('Y' or 'N') CHAR(1) ('T' or 'F')

Date and time types
Mapping type Java type ANSI SQL Type

TUTORIALS POINT Simply Easy Learning

date time timestamp calendar calendar_date

java.util.Date or java.sql.Date java.util.Date or java.sql.Time java.util.Date or java.sql.Timestamp java.util.Calendar java.util.Calendar

DATE TIME TIMESTAMP TIMESTAMP DATE

Binary and large object types
Mapping type binary text serializable clob blob Java type byte[] java.lang.String any Java class that implements java.io.Serializable java.sql.Clob java.sql.Blob ANSI SQL Type VARBINARY (or BLOB) CLOB VARBINARY (or BLOB) CLOB BLOB

JDK-related types
Mapping type class locale timezone currency Java type java.lang.Class java.util.Locale java.util.TimeZone java.util.Currency ANSI SQL Type VARCHAR VARCHAR VARCHAR VARCHAR

TUTORIALS POINT Simply Easy Learning

this.firstName = fname. it's important to provide JavaBeans compliant code as well as one attribute which would work as index like id attribute in the Employee class. private String firstName. } public void setId( int id ) { this. Create POJO Classes The first step in creating an application is to build the Java POJO class or classes.firstName = first_name. private String lastName. this.salary = salary. } public String getLastName() { TUTORIALS POINT Simply Easy Learning .id = id. private int salary. Let us consider our Employee class with getXXX andsetXXX methods to make it JavaBeans compliant class. public class Employee { private int id.lastName = lname. depending on the application that will be persisted to the database. public Employee() {} public Employee(String fname. We will go through different steps involved in creating Java Application using Hibernate technology. int salary) { this. } public int getId() { return id. All normal Java objects are POJO. } public void setFirstName( String first_name ) { this. A POJO (Plain Old Java Object) is a Java object that doesn't extend or implement some specialized classes and interfaces respectively required by the EJB framework. String lname. When you design a classs to be persisted by Hibernate. } public String getFirstName() { return firstName.CHAPTER 10 Hibernate Examples L et us try an example of using Hibernate to provide Java persistence in a standalone application.

return lastName. } public void setSalary( int salary ) { this. } public void setLastName( String last_name ) { this. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>.hbm.hbm.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. Create Mapping Configuration File This step is to create a mapping file that instructs Hibernate how to map the defined class or classes to the database tables.lastName = last_name. Consider above objects need to be stored and retrieved into the following RDBMS table: create table EMPLOYEE ( id INT NOT NULL auto_increment.hibernate. first_name VARCHAR(20) default NULL. salary INT default NULL. } public int getSalary() { return salary. TUTORIALS POINT Simply Easy Learning .xml.salary = salary.xml.0.org/dtd/hibernate-mapping-3. We saved our mapping document in the file Employee. <?xml version="1. } } Create Database Tables Second step would be creating tables in your database. There would be one table corresponding to each object you are willing to provide persistence. last_name VARCHAR(20) default NULL. PRIMARY KEY (id) ). Let us see little detail about the mapping document:  The mapping document is an XML document having <hibernate-mapping> as the root element which contains all the <class> elements.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.

err.util. The <class> elements are used to define specific mappings from a Java classes to the database tables. import java.Iterator. Create Application Class Finally. org. The <generator> element within the id element is used to automatically generate the primary key values. /* List down all the employees */ ME. } ManageEmployee ME = new ManageEmployee().addEmployee("John".configure().updateEmployee(empID1. 1000).SessionFactory. import import import import import org.HibernateException. Set the class attribute of the generator element is set to native to let hibernate pick up either identity. this mapping types will convert from Java to SQL data type.List.cfg.hibernate. "Paul". /* Add few employee records in database */ Integer empID1 = ME. /* Update employee's records */ ME.buildSessionFactory(). throw new ExceptionInInitializerError(ex)." + ex). The <meta> element is optional element and can be used to create the class description. we will create our application class with the main() method to run the application. Integer empID2 = ME.hibernate.listEmployees(). 10000).util.println("Failed to create sessionFactory object.hibernate. "Das".addEmployee("Zara".hibernate. 5000). public class ManageEmployee { private static SessionFactory factory. }catch (Throwable ex) { System. import java. "Ali". public static void main(String[] args) { try{ factory = new Configuration().Transaction. 5000).Date.hibernate. The <property> element is used to map a Java class property to a column in the database table.addEmployee("Daisy".Configuration. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database. TUTORIALS POINT Simply Easy Learning . The <id> element maps the unique ID attribute in class to the primary key of the database table. this mapping types will convert from Java to SQL data type.Session. Integer empID3 = ME. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. import java.util. org. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute. The type attribute holds the hibernate mapping type.     There are other attributes and elements available which will be used in a mapping document and I would try to cover as many as possible while discussing other Hibernate related topics. org. We will use this application to save few Employee's records and then we will apply CRUD operations on those records. The type attribute holds the hibernate mapping type. org.

Transaction tx = null. } tx.print(" Last Name: " + employee.rollback().listEmployees().commit().printStackTrace(). Employee employee = new Employee(fname. Transaction tx = null.commit(). e.close().deleteEmployee(empID2).createQuery("FROM Employee").openSession().out.rollback().openSession(). }catch (HibernateException e) { if (tx!=null) tx. }finally { session. /* List down new list of the employees */ ME. EmployeeID).print("First Name: " + employee. e. String lname. }catch (HibernateException e) { if (tx!=null) tx. for (Iterator iterator = employees. Transaction tx = null.getLastName()). try{ tx = session.beginTransaction().out.close().printStackTrace(). List employees = session./* Delete an employee from the database */ ME. employee.get(Employee.getSalary()). lname.){ Employee employee = (Employee) iterator. TUTORIALS POINT Simply Easy Learning .hasNext().commit(). } /* Method to CREATE an employee in the database */ public Integer addEmployee(String fname.close(). } return employeeID. try{ tx = session.openSession(). }catch (HibernateException e) { if (tx!=null) tx. iterator. try{ tx = session.println(" Salary: " + employee.save(employee).class. }finally { session.rollback(). tx. e.out. Integer employeeID = null.beginTransaction().openSession().beginTransaction(). int salary){ Session session = factory. tx.iterator(). System. System. } } /* Method to UPDATE salary for an employee */ public void updateEmployee(Integer EmployeeID. } } /* Method to DELETE an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory.next(). System.printStackTrace().setSalary( salary ).update(employee). salary).list(). int salary ){ Session session = factory. }finally { session. } /* Method to READ all the employees */ public void listEmployees( ){ Session session = factory. session. employeeID = (Integer) session. Employee employee = (Employee)session. Transaction tx = null.getFirstName()).

e.      Create hibernate.VARIOUS LOG MESSAGES WILL DISPLAY HERE.try{ tx = session...beginTransaction().. EmployeeID). and records would be created in EMPLOYEE table.. Execute ManageEmployee binary to run the program..class..xml configuration file as explained in configuration chapter.hbm.commit(). it should have following records: mysql> select * from EMPLOYEE.delete(employee).00 sec mysql> TUTORIALS POINT Simply Easy Learning . tx. $java ManageEmployee . You would get following result.xml mapping file as shown above. Employee employee = (Employee)session.. Create Employee... } } } Compilation and Execution Here are the steps to compile and run the above mentioned application. }catch (HibernateException e) { if (tx!=null) tx.close(). +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 29 | Zara | Ali | 5000 | | 31 | John | Paul | 10000 | +----+------------+-----------+--------+ 2 rows in set (0. Create ManageEmployee..cfg.java source file as shown above and compile it. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution. First First First First First Name: Name: Name: Name: Name: Zara Daisy John Zara John Last Name: Ali Salary: 1000 Last Name: Das Salary: 5000 Last Name: Paul Salary: 10000 Last Name: Ali Salary: 5000 Last Name: Paul Salary: 10000 If you check your EMPLOYEE table. session.java source file as shown above and compile it.rollback()... Create Employee.printStackTrace(). }finally { session..get(Employee.

util.util. sets contain no pair of elements e1 and e2 such that e1. the mapping of associations between entity classes and Component Mappings.ArrayList This is mapped with a <map> element and initialized with java.Set. The sort attribute can be set to either a comparator or natural ordering. java. they are rarely used so I'm not going to discuss them in this tutorial.util.util.TreeMap.HashSet This is mapped with a <set> element and initialized with java. These are the mapping of collections. Hibernate Set Mappings A Set is a java collection that does not contain any duplicate element.util. So objects to be added to a set must TUTORIALS POINT Simply Easy Learning . java. If you want to map a user defined collection interfaces which is not directly supported by Hibernate. Collections Mappings If an entity or class has collection of values for a particular variable. java.util.TreeSet.Set java.util.util. Hibernate can persist instances of java. then we can map those values using any one of the collection interfaces available in java.Map.util.SortedMap.util.List java. Collection type java.Map Mapping and Description This is mapped with a <set> element and initialized with java.HashMap This is mapped with a <map> element and initialized with java.SortedMap Arrays are supported by Hibernate with <primitive-array> for Java primitive value types and <array> for everything else.equals(e2).util. and any array of persistent entities or values. This is mapped with a <list> element and initialized with java.util. The sort attribute can be set to either a comparator or natural ordering.util.Collection java. More formally. java.util.util.SortedSet. However.ArrayList This is mapped with a <bag> or <ibag> element and initialized with java. you need to tell Hibernate about the semantics of your custom collections which is not very easy and not recommend to be used.util. java.util.List.SortedSet java.CHAPTER 11 Hibernate O/R Mapping S o far we have seen very basic O/R mapping using hibernate but there are three most important mapping topics which we have to learn in detail. and at most one null element.

id = id. employee_id INT default NULL.lastName = lname.util. int salary) { this. public class Employee { private int id. A Set is mapped with a <set> element in the mapping table and initialized with java. private Set certificates. this. private String firstName. private String lastName.firstName = fname. certificate_name VARCHAR(30) default NULL. PRIMARY KEY (id) ). String lname. PRIMARY KEY (id) ). You can use Set collection in your class when there is no duplicate element required in the collection.HashSet. last_name VARCHAR(20) default NULL.salary = salary. private int salary. } public int getId() { return id. Define RDBMS Tables Consider a situation where we need to store our employee records in EMPLOYEE table which will have following structure: create table EMPLOYEE ( id INT NOT NULL auto_increment. first_name VARCHAR(20) default NULL. assume each employee can have one or more certificate associated with him/her. } public void setId( int id ) { this. So we will store certificate related information in a separate table which has following structure: create table CERTIFICATE ( id INT NOT NULL auto_increment. import java.implement both the equals() and hashCode() methods so that Java can determine whether any two elements/objects are identical. public Employee() {} public Employee(String fname. } public String getFirstName() { TUTORIALS POINT Simply Easy Learning .*. There will be one-to-many relationship between EMPLOYEE and CERTIFICATE objects: Define POJO Classes Let us implement our POJO class Employee which will be used to persist the objects related to EMPLOYEE table and having a collection of certificates in Set variable. salary INT default NULL.util. Further. this.

equals(obj. private String name.getClass())) return false. } public void setName( String name ) { this.getName()))) { return true. } public String getLastName() { return lastName. } } Now let us define another POJO class corresponding to CERTIFICATE table so that certificate objects can be stored and retrieved into the CERTIFICATE table.certificates = certificates. } public int getId() { return id.name = name. } public void setCertificates( Set certificates ) { this.salary = salary. } return false.name. } public void setLastName( String last_name ) { this.lastName = last_name. if((this.id = id.hashCode(). This class should also implement both the equals() and hashCode() methods so that Java can determine whether any two elements/objects are identical.id == obj2. } public void setId( int id ) { this. if (!this. TUTORIALS POINT Simply Easy Learning . public class Certificate { private int id.name = name. } public int hashCode() { int tmp = 0.getClass().getId()) && (this. } public void setSalary( int salary ) { this.return firstName. tmp = ( id + name ). } public void setFirstName( String first_name ) { this. } public boolean equals(Object obj) { if (obj == null) return false.firstName = first_name. } public Set getCertificates() { return certificates. } public String getName() { return name. } public int getSalary() { return salary. public Certificate() {} public Certificate(String name) { this. Certificate obj2 = (Certificate)obj.equals(obj2.

TUTORIALS POINT Simply Easy Learning . } } Define Hibernate Mapping File Let us develop our mapping file which instructs Hibernate how to map the defined classes to the database tables.xml. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.  The <generator> element within the id element is used to automatically generate the primary key values. The type attribute holds the hibernate mapping type.hbm. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <set name="certificates" cascade="all"> <key column="employee_id"/> <one-to-many class="Certificate"/> </set> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> <class name="Certificate" table="CERTIFICATE"> <meta attribute="class-description"> This class contains the certificate records.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. <?xml version="1.org/dtd/hibernate-mapping-3. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="name" column="certificate_name" type="string"/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>. The <set> element will be used to define the rule for Set collection used. contains two <class> elements corresponding to each class. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. We saved our mapping document in the file Employee.return tmp.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www. sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database.0.xml. Set the class attribute of the generator element is set to native to let hibernate pick up either identity.hbm.  The <meta> element is optional element and can be used to create the class description. You are already familiar with most of the mapping detail but let us see all the elements of mapping file once again:  The mapping document is an XML document having <hibernate-mapping> as the root element which  The <class> elements are used to define specific mappings from a Java classes to the database tables.  The <id> element maps the unique ID attribute in class to the primary key of the database table. this mapping types will convert from Java to SQL data type.hibernate.

SessionFactory. For each set variable. org. import import import import import org.buildSessionFactory().Configuration. } ManageEmployee ME = new ManageEmployee(). org.  The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object ie.util.  The <set> element is new here and has been introduced to set the relationship between Certificate and Employee classes. org. table EMPLOYEE.hibernate.println("Failed to create sessionFactory object.add(new Certificate("MBA")). in our case it is certificates. /* Add employee records in the database */ Integer empID1 = ME.hibernate. set1). We used the cascade attribute in the <set> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects. set2.hibernate.cfg. 4000.add(new Certificate("BCA")). this mapping types will convert from Java to SQL data type. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. We will use this application to save few Employee's records alongwith their certificates and then we will apply CRUD operations on those records. /* Delete an employee from the database */ TUTORIALS POINT Simply Easy Learning . Create Application Class Finally. org.add(new Certificate("PMP")). "Kumar". "Kumar".addEmployee("Manoj". as such. The type attribute holds the hibernate mapping type.  The <one-to-many> element indicates that one Employee object relates to many Certificate objects and.Transaction. }catch (Throwable ex) { System. The <property> element is used to map a Java class property to a column in the database table. 3000. throw new ExceptionInInitializerError(ex).hibernate. set1. <many-to-one> or <many-to-many> elements based on your requirement. The nameattribute is set to the defined Set variable in the parent class. /* Another set of certificates for the second employee HashSet set2 = new HashSet().add(new Certificate("BA")). /* Update employee's salary records */ ME.HibernateException.updateEmployee(empID1. set1. */ /* Add another employee record in the database */ Integer empID2 = ME. set1.hibernate. import java.*. You can use either <one-toone>.err." + ex). set2). the Certificate object must have a Employee parent associated with it. /* List down all the employees */ ME. set2. we need to define a separate set element in the mapping file. we will create our application class with the main() method to run the application.configure(). 5000). /* Let us have a set of certificates for the first employee */ HashSet set1 = new HashSet(). public class ManageEmployee { private static SessionFactory factory.Session.add(new Certificate("MCA")). public static void main(String[] args) { try{ factory = new Configuration().addEmployee("Dilip".listEmployees().

} } /* Method to update salary for an employee */ public void updateEmployee(Integer EmployeeID.println("Certificate: " + certName.commit(). try{ tx = session.){ Certificate certName = (Certificate) iterator2.setCertificates(cert).class.out. } } tx. Set cert){ Session session = factory.commit().out.beginTransaction().beginTransaction(). }catch (HibernateException e) { TUTORIALS POINT Simply Easy Learning .rollback(). for (Iterator iterator1 = employees.println(" Salary: " + employee.commit().getSalary()).setSalary( salary ). } /* Method to add an employee record in the database */ public Integer addEmployee(String fname.getLastName()). for (Iterator iterator2 = certificates. Transaction tx = null.close().update(employee).listEmployees(). employee.ME.save(employee).printStackTrace(). Employee employee = (Employee)session. try{ tx = session.openSession(). System. e. iterator1.next(). /* List down all the employees */ ME. Integer employeeID = null.hasNext().getName()).rollback(). } /* Method to list all the employees detail */ public void listEmployees( ){ Session session = factory.iterator().){ Employee employee = (Employee) iterator1.print(" Last Name: " + employee.out. }finally { session. Employee employee = new Employee(fname. }catch (HibernateException e) { if (tx!=null) tx. int salary. lname.openSession(). Transaction tx = null.getFirstName()). System. }finally { session. employee. iterator2. e. Set certificates = employee. salary).print("First Name: " + employee.deleteEmployee(empID2).getCertificates(). tx.next().createQuery("FROM Employee"). List employees = session. int salary ){ Session session = factory. tx. String lname.close(). EmployeeID).hasNext(). employeeID = (Integer) session. try{ tx = session.printStackTrace(). }catch (HibernateException e) { if (tx!=null) tx.openSession().list().out. session. Transaction tx = null.beginTransaction(). System.get(Employee. } return employeeID.iterator(). System.

session. } } /* Method to delete an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory.. e. and same time records would be created in EMPLOYEE and CERTIFICATE tables.commit().java source file as shown above and compile it.cfg. Execute ManageEmployee binary to run the program. }finally { session.rollback()..VARIOUS LOG MESSAGES WILL DISPLAY HERE..hbm..delete(employee). Employee employee = (Employee)session. } } } Compilation and Execution Here are the steps to compile and run the above mentioned application. Create ManageEmployee. Create Certificate.xml mapping file as shown above. $java ManageEmployee .. Create Employee.java source file as shown above and compile it. try{ tx = session.get(Employee. Create Employee.openSession()....rollback().beginTransaction().printStackTrace().class.close(). }finally { session. tx. e. }catch (HibernateException e) { if (tx!=null) tx. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution. You would get following result on the screen.close().. First Name: Manoj Certificate: MBA Certificate: PMP Certificate: MCA First Name: Dilip Certificate: BCA Certificate: BA First Name: Manoj Certificate: MBA Certificate: PMP Last Name: Kumar Salary: 4000 Last Name: Kumar Last Name: Kumar Salary: 3000 Salary: 5000 TUTORIALS POINT Simply Easy Learning ...java source file as shown above and compile it. EmployeeID). Transaction tx = null..if (tx!=null) tx.printStackTrace()..xml configuration file as explained in configuration chapter.       Create hibernate.

+----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0. PRIMARY KEY (id) ). Further. employee_id INT default NULL.TreeSet. first_name VARCHAR(20) default NULL.Certificate: MCA If you check your EMPLOYEE and CERTIFICATE tables.00 sec) mysql> select * from certificate. assume each employee can have one or more certificate associated with him/her. A SortedSet is mapped with a <set> element in the mapping table and initialized with java.00 sec) mysql> Hibernate SortedSet Mappings A SortedSet is a java collection that does not contain any duplicate element and elements are ordered using their natural ordering or by a comparator provided. Define RDBMS Tables Consider a situation where we need to store our employee records in EMPLOYEE table which will have following structure: create table EMPLOYEE ( id INT NOT NULL auto_increment. PRIMARY KEY (id) ). certificate_name VARCHAR(30) default NULL. So we will store certificate related information in a separate table which has following structure: create table CERTIFICATE ( id INT NOT NULL auto_increment. The sort attribute can be set to either a comparator or natural ordering. There will be one-to-many relationship between EMPLOYEE and CERTIFICATE objects: TUTORIALS POINT Simply Easy Learning . they should have following records: mysql> select * from employee. +----+------------------+-------------+ | id | certificate_name | employee_id | +----+------------------+-------------+ | 1 | MBA | 1 | | 2 | PMP | 1 | | 3 | MCA | 1 | +----+------------------+-------------+ 3 rows in set (0. If we use natural ordering then its iterator will traverse the set in ascending element order. salary INT default NULL.util. last_name VARCHAR(20) default NULL.

} public void setFirstName( String first_name ) { this. private String lastName. import java. } public void setSalary( int salary ) { this. String lname. public Employee() {} public Employee(String fname. } public int getSalary() { return salary. } public int getId() { return id. } public String getLastName() { return lastName. } public void setCertificates( SortedSet certificates ) { this. this. private SortedSet certificates.salary = salary.lastName = lname. This class should also implement Comparable interface and compareTo method which will be used to sort the elements in case you setsort="natural" in your mapping file (see below mapping file). private int salary. int salary) { this. } public String getFirstName() { return firstName.certificates = certificates. private String firstName.util. } public void setLastName( String last_name ) { this. public class Employee { private int id.salary = salary.id = id.*. } public void setId( int id ) { this. } } Now let us define another POJO class corresponding to CERTIFICATE table so that certificate objects can be stored and retrieved into the CERTIFICATE table. } public SortedSet getCertificates() { return certificates. public class Certificate implements Comparable <Certificate>{ TUTORIALS POINT Simply Easy Learning .firstName = fname. this.Define POJO Classes Let us implement our POJO class Employee which will be used to persist the objects related to EMPLOYEE table and having a collection of certificates in SortedSet variable.firstName = first_name.lastName = last_name.

} public int compareTo(Certificate that){ final int BEFORE = -1.compareTo(thatCertificate). public Certificate() {} public Certificate(String name) { this. } else { return thisCertificate. } else if(thatCertificate == null) { return BEFORE. } public void setName( String name ) { this. private String name.0. if (that == null) { return BEFORE.hibernate. } Comparable thisCertificate = this. } } } Define Hibernate Mapping File Let us develop our mapping file which instructs Hibernate how to map the defined classes to the database tables.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. Comparable thatCertificate = that.id = id.name = name. <?xml version="1.getName(). final int AFTER = 1. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <set name="certificates" cascade="all" sort="MyClass"> <key column="employee_id"/> TUTORIALS POINT Simply Easy Learning .getName(). } public void setId( int id ) { this.name = name. The <set> element will be used to define the rule for SortedSet collection used. } public String getName() { return name.private int id. } public int getId() { return id. if(thisCertificate == null) { return AFTER.org/dtd/hibernate-mapping-3.

You are already familiar with most of the mapping detail but let us see all the elements of mapping file once again:  The mapping document is an XML document having <hibernate-mapping> as the root element which contains two <class> elements corresponding to each class.  The <set> element is used to set the relationship between Certificate and Employee classes.xml.  The <one-to-many> element indicates that one Employee object relates to many Certificate objects and. import java. The type attribute holds the hibernate mapping type. We used the cascade attribute in the <set> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute. <many-to-one> or <many-to-many> elements based on your requirement. the Certificate object must have a Employee parent associated with it. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table.xml.  The <property> element is used to map a Java class property to a column in the database table.hbm.  The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object ie.<one-to-many class="Certificate"/> </set> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> <class name="Certificate" table="CERTIFICATE"> <meta attribute="class-description"> This class contains the certificate records.util. as such. table EMPLOYEE. this mapping types will convert from Java to SQL data type. The name attribute is set to the definedSortedSet variable in the parent class. We have used a class MyClass which implements java. If we use sort="natural" setting then we do not need to create a separate class because Certificate class already has implemented Comparable interface and hibernate will use compareTo() method defined in Certificate class to compare certificate names.  The <id> element maps the unique ID attribute in class to the primary key of the database table. this mapping types will convert from Java to SQL data type. The sort attribute can be set to natural to have natural sorting or it can be set to a custom class implementingjava.Comparator. Set the class attribute of the generator element is set to native to let hibernate pick up either identity.  The <meta> element is optional element and can be used to create the class description.util. You can use either <one-toone>. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table.Comparator to reverse the sorting order implemented in Certificate class. Let us do descending sorting in this class using this class.  The <class> elements are used to define specific mappings from a Java classes to the database tables.Comparator.hbm.  The <generator> element within the id element is used to automatically generate the primary key values. in our case it is certificates. TUTORIALS POINT Simply Easy Learning . </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="name" column="certificate_name" type="string"/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>. The type attribute holds the hibernate mapping type. sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database. But we are using a custom comparator class MyClass in our mapping file so we would have to create this class based on our sorting algorithm.util. We saved our mapping document in the file Employee.

/* Add employee records in the database */ Integer empID1 = ME. throw new ExceptionInInitializerError(ex).Configuration.hibernate. /* Let us have a set of certificates for the first employee */ TreeSet set1 = new TreeSet().hibernate. public class ManageEmployee { private static SessionFactory factory.println("Failed to create sessionFactory object. org. } } } Create Application Class Finally. } ManageEmployee ME = new ManageEmployee(). org.hibernate. set1. set2). } else if(thatCertificate == null) { return BEFORE * -1. Certificate o2) { final int BEFORE = -1.HibernateException.getName(). org. final int AFTER = 1.addEmployee("Dilip".configure(). public static void main(String[] args) { try{ factory = new Configuration(). multiple by -1 */ if (o2 == null) { return BEFORE * -1. set2.public class MyClass implements Comparator<Certificate>{ public int compare(Certificate o1.add(new Certificate("BA")).add(new Certificate("MBA")).add(new Certificate("MCA")). */ /* Add another employee record in the database */ Integer empID2 = ME.buildSessionFactory().*. import import import import import org.err. import java.cfg. We will use this application to save few Employee's records alongwith their certificates and then we will apply CRUD operations on those records.compareTo(thatCertificate) * -1. we will create our application class with the main() method to run the application.getName(). /* To reverse the sorting order.add(new Certificate("PMP")). "Kumar". set2. set1).util. Comparable thatCertificate = o2. } Comparable thisCertificate = o1. }catch (Throwable ex) { System.addEmployee("Manoj". /* Another set of certificates for the second employee TreeSet set2 = new TreeSet().Session. if(thisCertificate == null) { return AFTER * 1. "Kumar"." + ex).Transaction.hibernate. set1. } else { return thisCertificate. 4000.hibernate. TUTORIALS POINT Simply Easy Learning .SessionFactory.add(new Certificate("BCA")). 3000. org. set1.

for (Iterator iterator2 = certificates.out. SortedSet certificates = employee. try{ tx = session.print("First Name: " + employee.getFirstName()).openSession().updateEmployee(empID1. tx.hasNext(). System. iterator1.out. employeeID = (Integer) session./* List down all the employees */ ME.close().close().printStackTrace(). }finally { session.save(employee).openSession(). System.getSalary()).list(). SortedSet cert){ Session session = factory. Employee employee = new Employee(fname.commit(). employee. } return employeeID. /* List down all the employees */ ME.next().createQuery("FROM Employee").println(" Salary: " + employee. Integer employeeID = null. salary).hasNext().getCertificates(). }catch (HibernateException e) { if (tx!=null) tx. Transaction tx = null.out. int salary ){ Session session = factory. } } /* Method to update salary for an employee */ public void updateEmployee(Integer EmployeeID. e.beginTransaction().printStackTrace().getName()).iterator(). System. try{ tx = session. /* Update employee's salary records */ ME.next().deleteEmployee(empID2).listEmployees(). /* Delete an employee from the database */ ME.commit().out. } } tx.beginTransaction(). Transaction tx = null. Transaction tx = null. try{ TUTORIALS POINT Simply Easy Learning .println("Certificate: " + certName. int salary.rollback(). String lname. iterator2.){ Employee employee = (Employee) iterator1.rollback(). } /* Method to list all the employees detail */ public void listEmployees( ){ Session session = factory.setCertificates(cert).listEmployees(). 5000). for (Iterator iterator1 = employees. } /* Method to add an employee record in the database */ public Integer addEmployee(String fname.){ Certificate certName = (Certificate) iterator2. }finally { session.iterator(). System. lname.getLastName()).openSession(). }catch (HibernateException e) { if (tx!=null) tx. List employees = session.print(" Last Name: " + employee. e.

..update(employee)..cfg.java source file as shown above and compile it.class.beginTransaction(). Create Employee.hbm... Execute ManageEmployee binary to run the program.xml mapping file as shown above.        Create hibernate. tx.. session. You would get following result on the screen.. }catch (HibernateException e) { if (tx!=null) tx. You can try by changing your mapping file.commit(). e. and same time records would be created in EMPLOYEE and CERTIFICATE tables.. Create ManageEmployee.xml configuration file as explained in configuration chapter. tx. employee.VARIOUS LOG MESSAGES WILL DISPLAY HERE.get(Employee.tx = session.. Employee employee = (Employee)session..openSession().. try{ tx = session.setSalary( salary ).printStackTrace(). }finally { session. You can see certificates has been sorted in reverse order. Transaction tx = null.java source file as shown above and compile it.beginTransaction().rollback().close().printStackTrace().rollback(). $java ManageEmployee . } } /* Method to delete an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory.java source file as shown above and compile it.get(Employee. simply set sort="natural" and execute your program and compare the results. e. Create Employee.class. }catch (HibernateException e) { if (tx!=null) tx.. Employee employee = (Employee)session. session. EmployeeID). Create MyClass. }finally { session.java source file as shown above and compile it. } } } Compilation and Execution Here are the steps to compile and run the above mentioned application. EmployeeID). First Name: Manoj Certificate: PMP Certificate: MCA Last Name: Kumar Salary: 4000 TUTORIALS POINT Simply Easy Learning .delete(employee).commit(). Create Certificate. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.close()..

00 sec) mysql> select * from certificate. +----+------------------+-------------+ | id | certificate_name | employee_id | +----+------------------+-------------+ | 1 | MBA | 1 | | 2 | PMP | 1 | | 3 | MCA | 1 | +----+------------------+-------------+ 3 rows in set (0. Define RDBMS Tables Consider a situation where we need to store our employee records in EMPLOYEE table which will have following structure: create table EMPLOYEE ( id INT NOT NULL auto_increment. first_name VARCHAR(20) default NULL. PRIMARY KEY (id) ).Certificate: MBA First Name: Dilip Certificate: BCA Certificate: BA First Name: Manoj Certificate: PMP Certificate: MCA Certificate: MBA Last Name: Kumar Last Name: Kumar Salary: 3000 Salary: 5000 If you check your EMPLOYEE and CERTIFICATE tables.ArrayList.00 sec) mysql> Hibernate List Mappings A List is a java collection that stores elements in sequence and allow duplicate elements. last_name VARCHAR(20) default NULL. and search for elements in the list.util. salary INT default NULL. A List is mapped with a <list> element in the mapping table and initialized with java. The user can access elements by their integer index. and they typically allow multiple null elements if they allow null elements at all. The user of this interface has precise control over where in the list each element is inserted. More formally. lists typically allow pairs of elements e1 and e2 such that e1. they should have following records: mysql> select * from employee.equals(e2). +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0. TUTORIALS POINT Simply Easy Learning .

private int salary.Further.id = id. private List certificates. The index column defines the position of the element in the collection. assume each employee can have one or more certificate associated with him/her.lastName = last_name. idx INT default NULL. private String lastName. Define POJO Classes Let us implement a POJO class Employee which will be used to persist the objects related to EMPLOYEE table and having a collection of certificates in List variable. } public int getId() { return id.*. TUTORIALS POINT Simply Easy Learning . } public void setId( int id ) { this. } public String getLastName() { return lastName. certificate_name VARCHAR(30) default NULL.util. PRIMARY KEY (id) ).salary = salary. } public String getFirstName() { return firstName.firstName = first_name. int salary) { this. public class Employee { private int id.salary = salary. } public List getCertificates() { return certificates. import java. A List collection mapping needs an index column in the collection table. } public void setLastName( String last_name ) { this. } public void setFirstName( String first_name ) { this. There will be one-to-many relationship between EMPLOYEE and CERTIFICATE objects. So we will store certificate related information in a separate table which has following structure: create table CERTIFICATE ( id INT NOT NULL auto_increment. String lname.lastName = lname. public Employee() {} public Employee(String fname. this. } public int getSalary() { return salary. } public void setSalary( int salary ) { this. this. employee_id INT default NULL.firstName = fname. private String firstName.

0. } } Define Hibernate Mapping File Let us develop our mapping file which instructs Hibernate how to map the defined classes to the database tables. public Certificate() {} public Certificate(String name) { this. } public void setName( String name ) { this. <?xml version="1.hibernate. } public void setId( int id ) { this. The <list> element will be used to define the rule for List collection used. The index of list is always of type integer and is mapped using the <list-index> element. } } We need to define another POJO class corresponding to CERTIFICATE table so that certificate objects can be stored and retrieved into the CERTIFICATE table.} public void setCertificates( List certificates ) { this. } public String getName() { return name.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.name = name.name = name.certificates = certificates. public class Certificate{ private int id. } public int getId() { return id.id = id. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <list name="certificates" cascade="all"> <key column="employee_id"/> <list-index column="idx"/> <one-to-many class="Certificate"/> </list> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> TUTORIALS POINT Simply Easy Learning .org/dtd/hibernate-mapping-3.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. private String name.

<class name="Certificate" table="CERTIFICATE"> <meta attribute="class-description"> This class contains the certificate records. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="name" column="certificate_name" type="string"/> </class> </hibernate-mapping>

You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping document in the file Employee.hbm.xml. You are already familiar with most of the mapping detail but let us see all the elements of mapping file once again:

 The mapping document is an XML document having <hibernate-mapping> as the root element which  The <class> elements are used to define specific mappings from a Java classes to the database tables. The  
Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute. The <meta> element is optional element and can be used to create the class description. The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. The <generator> element within the id element is used to automatically generate the primary key values. Set the class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database. The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. The <list> element is used to set the relationship between Certificate and Employee classes. We used the cascade attribute in the <list> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects. The name attribute is set to the defined Listvariable in the parent class, in our case it is certificates. The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object ie. table EMPLOYEE. The <list-index> element is used to keep the position of the element and map with the index column in the collection table. The index of the persistent list starts at zero. You could change this, for example, with <listindex base="1".../> in your mapping. The <one-to-many> element indicates that one Employee object relates to many Certificate objects and, as such, the Certificate object must have a Employee parent associated with it. You can use either <one-toone>, <many-to-one> or <many-to-many> elements based on your requirement. If we changed this example to use a many-to-many relationship, we would need an association table to map between the parent and the child objects. contains two <class> elements corresponding to each class.

 

  

Create Application Class

Finally, we will create our application class with the main() method to run the application. We will use this application to save few Employee's records alongwith their certificates and then we will apply CRUD operations on those records.
import java.util.*; import import import import org.hibernate.HibernateException; org.hibernate.Session; org.hibernate.Transaction; org.hibernate.SessionFactory;

TUTORIALS POINT Simply Easy Learning

import org.hibernate.cfg.Configuration; public class ManageEmployee { private static SessionFactory factory; public static void main(String[] args) { try{ factory = new Configuration().configure().buildSessionFactory(); }catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex); } ManageEmployee ME = new ManageEmployee(); /* Let us have a set of certificates for the first employee */ ArrayList set1 = new ArrayList(); set1.add(new Certificate("MCA")); set1.add(new Certificate("MBA")); set1.add(new Certificate("PMP")); /* Add employee records in the database */ Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, set1); /* Another set of certificates for the second employee ArrayList set2 = new ArrayList(); set2.add(new Certificate("BCA")); set2.add(new Certificate("BA")); */

/* Add another employee record in the database */ Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, set2); /* List down all the employees */ ME.listEmployees(); /* Update employee's salary records */ ME.updateEmployee(empID1, 5000); /* Delete an employee from the database */ ME.deleteEmployee(empID2); /* List down all the employees */ ME.listEmployees(); } /* Method to add an employee record in the database */ public Integer addEmployee(String fname, String lname, int salary, ArrayList cert){ Session session = factory.openSession(); Transaction tx = null; Integer employeeID = null; try{ tx = session.beginTransaction(); Employee employee = new Employee(fname, lname, salary); employee.setCertificates(cert); employeeID = (Integer) session.save(employee); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } return employeeID; } /* Method to list all the employees detail */ public void listEmployees( ){ Session session = factory.openSession(); Transaction tx = null;

TUTORIALS POINT Simply Easy Learning

try{ tx = session.beginTransaction(); List employees = session.createQuery("FROM Employee").list(); for (Iterator iterator1 = employees.iterator(); iterator1.hasNext();){ Employee employee = (Employee) iterator1.next(); System.out.print("First Name: " + employee.getFirstName()); System.out.print(" Last Name: " + employee.getLastName()); System.out.println(" Salary: " + employee.getSalary()); List certificates = employee.getCertificates(); for (Iterator iterator2 = certificates.iterator(); iterator2.hasNext();){ Certificate certName = (Certificate) iterator2.next(); System.out.println("Certificate: " + certName.getName()); } } tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } } /* Method to update salary for an employee */ public void updateEmployee(Integer EmployeeID, int salary ){ Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, EmployeeID); employee.setSalary( salary ); session.update(employee); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } } /* Method to delete an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, EmployeeID); session.delete(employee); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } } }

Compilation and Execution
Here are the steps to compile and run the above mentioned application. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.

Create hibernate.cfg.xml configuration file as explained in configuration chapter.

TUTORIALS POINT Simply Easy Learning

TUTORIALS POINT Simply Easy Learning ..java source file as shown above and compile it. You can try by changing your mapping file. $java ManageEmployee . and same time records would be created in EMPLOYEE and CERTIFICATE tables. Create ManageEmployee.. simply set sort="natural" and execute your program and compare the results. Create Certificate. You would get following result on the screen.. +----+------------------+------+-------------+ | id | certificate_name | idx | employee_id | +----+------------------+------+-------------+ | 6 | MCA | 0 | 51 | | 7 | MBA | 1 | 51 | | 8 | PMP | 2 | 51 | +----+------------------+------+-------------+ 3 rows in set (0.. they should have following records: mysql> select * from EMPLOYEE.hbm..00 sec) mysql> select * from CERTIFICATE..java source file as shown above and compile it.. Hibernate applications rarely use arrays.xml mapping file as shown above. You can see certificates has been sorted in reverse order.     Create Employee.java source file as shown above and compile it. except with different element and attribute names (<array> and <array-index>).VARIOUS LOG MESSAGES WILL DISPLAY HERE..00 sec mysql> Alternatively. Execute ManageEmployee binary to run the program. Create Employee. you could map a Java array instead of a list.. for reasons explained earlier.. A array mapping is virtually identical to the previous example.. First Name: Manoj Certificate: MCA Certificate: MBA Certificate: PMP First Name: Dilip Certificate: BCA Certificate: BA First Name: Manoj Certificate: MCA Certificate: MBA Certificate: PMP Last Name: Kumar Salary: 4000 Last Name: Kumar Last Name: Kumar Salary: 3000 Salary: 5000 If you check your EMPLOYEE and CERTIFICATE tables. +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 51 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0... However.

private int salary. certificate_name VARCHAR(30) default NULL. String lname.firstName = fname. We will store certificate related information in a separate table which has following structure: create table CERTIFICATE ( id INT NOT NULL auto_increment. employee_id INT default NULL. int salary) { this. A Collection is mapped with a <bag> element in the mapping table and initialized with java.lastName = lname. first_name VARCHAR(20) default NULL.ArrayList. this. import java.id = id. private Collection certificates. A bag is a random grouping of the objects in the list. Define RDBMS Tables Consider a situation where we need to store our employee records in EMPLOYEE table which will have following structure: create table EMPLOYEE ( id INT NOT NULL auto_increment. public class Employee { private int id. Further.Hibernate Bag Mappings A Bag is a java collection that stores elements without caring about the sequencing but allow duplicate elements in the list.salary = salary. last_name VARCHAR(20) default NULL.*. salary INT default NULL.util. } public String getFirstName() { TUTORIALS POINT Simply Easy Learning . public Employee() {} public Employee(String fname. Define POJO Classes Let us implement a POJO class Employee which will be used to persist the objects related to EMPLOYEE table and having a collection of certificates in List variable. PRIMARY KEY (id) ). assume each employee can have one or more certificate associated with him/her.util. private String lastName. } public void setId( int id ) { this. private String firstName. this. PRIMARY KEY (id) ). There will be one-to-many relationship between EMPLOYEE and CERTIFICATE objects. } public int getId() { return id.

name = name.hibernate.certificates = certificates. } public void setId( int id ) { this.salary = salary. <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www. } public void setSalary( int salary ) { this.id = id. } } We need to define another POJO class corresponding to CERTIFICATE table so that certificate objects can be stored and retrieved into the CERTIFICATE table.0. } public int getSalary() { return salary.name = name. } public void setCertificates( Collection certificates ) { this. } } Define Hibernate Mapping File Let us develop our mapping file which instructs Hibernate how to map the defined classes to the database tables. The <bag> element will be used to define the rule for the Collection used. } public String getLastName() { return lastName. } public int getId() { return id.org/dtd/hibernate-mapping-3. private String name.return firstName. } public void setLastName( String last_name ) { this.dtd"> TUTORIALS POINT Simply Easy Learning . } public String getName() { return name. } public void setFirstName( String first_name ) { this.firstName = first_name. } public Collection getCertificates() { return certificates. } public void setName( String name ) { this.lastName = last_name. public Certificate() {} public Certificate(String name) { this. public class Certificate{ private int id.

table EMPLOYEE. The <property> element is used to map a Java class property to a column in the database table. You can use either <one-toone>. The <bag> element is used to set the relationship between Certificate and Employee classes. The <id> element maps the unique ID attribute in class to the primary key of the database table. We used the cascade attribute in the <bag> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects.<hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail.xml. The <generator> element within the id element is used to automatically generate the primary key values.hbm. We saved our mapping document in the file Employee. The <one-to-many> element indicates that one Employee object relates to many Certificate objects and. The type attribute holds the hibernate mapping type. TUTORIALS POINT Simply Easy Learning . the Certificate object must have a Employee parent associated with it. The type attribute holds the hibernate mapping type.hbm. this mapping types will convert from Java to SQL data type. in our case it is certificates. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.xml. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <bag name="certificates" cascade="all"> <key column="employee_id"/> <one-to-many class="Certificate"/> </bag> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> <class name="Certificate" table="CERTIFICATE"> <meta attribute="class-description"> This class contains the certificate records. The <class> elements are used to define specific mappings from a Java classes to the database tables. You are already familiar with most of the mapping detail but let us see all the elements of mapping file once again:          The mapping document is an XML document having <hibernate-mapping> as the root element which contains two <class> elements corresponding to each class. Set the class attribute of the generator element is set to native to let hibernate pick up either identity. The name attribute is set to the definedCollection variable in the parent class. The <meta> element is optional element and can be used to create the class description. this mapping types will convert from Java to SQL data type. as such. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="name" column="certificate_name" type="string"/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>. <many-to-one> or <many-to-many> elements based on your requirement. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object ie. sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database.

TUTORIALS POINT Simply Easy Learning . ArrayList cert){ Session session = factory. int salary.util. salary). lname.println("Failed to create sessionFactory object. Transaction tx = null.HibernateException.addEmployee("Dilip". public class ManageEmployee { private static SessionFactory factory.hibernate. we will create our application class with the main() method to run the application. set1.configure(). Employee employee = new Employee(fname.updateEmployee(empID1. throw new ExceptionInInitializerError(ex). 4000. org.add(new Certificate("BCA")).Session.hibernate.listEmployees().cfg. set1.hibernate. "Kumar".hibernate. try{ tx = session. import import import import import org. /* Let us have a set of certificates for the first employee */ ArrayList set1 = new ArrayList().deleteEmployee(empID2).SessionFactory. /* Another set of certificates for the second employee ArrayList set2 = new ArrayList().add(new Certificate("BA")). org. set1). employee. org. String lname. 3000. */ /* Add another employee record in the database */ Integer empID2 = ME.addEmployee("Manoj". /* List down all the employees */ ME. /* List down all the employees */ ME." + ex).hibernate.openSession(). /* Update employee's salary records */ ME.setCertificates(cert). import java. Integer employeeID = null.Transaction. }catch (Throwable ex) { System.beginTransaction(). 5000).Create Application Class Finally.*. We will use this application to save few Employee's records alongwith their certificates and then we will apply CRUD operations on those records. /* Add employee records in the database */ Integer empID1 = ME. org.buildSessionFactory(). } /* Method to add an employee record in the database */ public Integer addEmployee(String fname.listEmployees().add(new Certificate("MCA")).add(new Certificate("PMP")). set2). /* Delete an employee from the database */ ME. set2.err.add(new Certificate("MBA")). "Kumar".Configuration. } ManageEmployee ME = new ManageEmployee(). set2. public static void main(String[] args) { try{ factory = new Configuration(). set1.

close(). }catch (HibernateException e) { if (tx!=null) tx. } } tx. tx. } return employeeID.println("Certificate: " + certName. try{ tx = session. int salary ){ Session session = factory. } } /* Method to update salary for an employee */ public void updateEmployee(Integer EmployeeID.printStackTrace().rollback().get(Employee. System.){ Certificate certName = (Certificate) iterator2. System. session.iterator().beginTransaction(). }finally { session. e.beginTransaction().){ Employee employee = (Employee) iterator1.printStackTrace(). List employees = session.hasNext().class.openSession().out. }finally { session.getSalary()).println(" Salary: " + employee.getCertificates().commit().out.getName()).commit(). try{ tx = session. System. Transaction tx = null.printStackTrace(). employee.close().next(). System. iterator1.iterator(). tx. }catch (HibernateException e) { TUTORIALS POINT Simply Easy Learning . }finally { session.update(employee). for (Iterator iterator2 = certificates.commit(). Collection certificates = employee.out. } } /* Method to delete an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory.beginTransaction().openSession().class. iterator2.print(" Last Name: " + employee.rollback().openSession().list().getLastName()). e. EmployeeID). }catch (HibernateException e) { if (tx!=null) tx. Transaction tx = null.commit(). Employee employee = (Employee)session.close().rollback(). e.employeeID = (Integer) session. EmployeeID). }catch (HibernateException e) { if (tx!=null) tx.save(employee).setSalary( salary ).out. tx.get(Employee. Employee employee = (Employee)session.hasNext().getFirstName()). try{ tx = session. } /* Method to list all the employees detail */ public void listEmployees( ){ Session session = factory. Transaction tx = null.print("First Name: " + employee. for (Iterator iterator1 = employees.next().delete(employee). session.createQuery("FROM Employee").

}finally { session... e.hbm.. You would get following result on the screen. +----+------------------+-------------+ | id | certificate_name | employee_id | +----+------------------+-------------+ TUTORIALS POINT Simply Easy Learning .VARIOUS LOG MESSAGES WILL DISPLAY HERE.cfg.xml mapping file as shown above.       Create hibernate. Create Certificate..java source file as shown above and compile it..java source file as shown above and compile it.00 sec) mysql> select * from CERTIFICATE.printStackTrace(). Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.close(). You can see certificates has been sorted in reverse order.. Execute ManageEmployee binary to run the program. First Name: Manoj Certificate: MCA Certificate: MBA Certificate: PMP First Name: Dilip Certificate: BCA Certificate: BA First Name: Manoj Certificate: MCA Certificate: MBA Certificate: PMP Last Name: Kumar Salary: 4000 Last Name: Kumar Last Name: Kumar Salary: 3000 Salary: 5000 If you check your EMPLOYEE and CERTIFICATE tables..rollback()..java source file as shown above and compile it..... +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 53 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0.if (tx!=null) tx. and same time records would be created in EMPLOYEE and CERTIFICATE tables. $java ManageEmployee .. Create ManageEmployee. they should have following records: mysql> select * from EMPLOYEE. You can try by changing your mapping file. Create Employee.xml configuration file as explained in configuration chapter. simply set sort="natural" and execute your program and compare the results. } } } Compilation and Execution Here are the steps to compile and run the above mentioned application. Create Employee.

The Map interface provides three collection views. TUTORIALS POINT Simply Easy Learning . Define RDBMS Tables Consider a situation where we need to store our employee records in EMPLOYEE table which will have following structure: create table EMPLOYEE ( id INT NOT NULL auto_increment. Define POJO Classes Let us implement a POJO class Employee which will be used to persist the objects related to EMPLOYEE table and having a collection of certificates in List variable. employee_id INT default NULL. private String lastName. certificate_type VARCHAR(40) default NULL. collection of values. which allow a map's contents to be viewed as a set of keys. last_name VARCHAR(20) default NULL. We will store certificate related information in a separate table which has following structure: create table CERTIFICATE ( id INT NOT NULL auto_increment.00 sec) mysql> Hibernate Map Mappings A Map is a java collection that stores elements in key-value pairs and does not allow duplicate elements in the list. public class Employee { private int id. PRIMARY KEY (id) ). certificate_name VARCHAR(30) default NULL.*.| 11 | MCA | 53 | | 12 | MBA | 53 | | 13 | PMP | 53 | +----+------------------+-------------+ 3 rows in set (0.HashMap. There will be one-to-many relationship between EMPLOYEE and CERTIFICATE objects. Further. assume each employee can have one or more certificate associated with him/her.util. or set of key-value mappings. first_name VARCHAR(20) default NULL. private String firstName. import java. PRIMARY KEY (id) ). salary INT default NULL. A Map is mapped with a <map> element in the mapping table and an unordered map can be initialized with java.util.

} public void setSalary( int salary ) { this. } public int getSalary() { return salary.firstName = first_name. private Map certificates. } public void setFirstName( String first_name ) { this. } public String getFirstName() { return firstName.salary = salary. } public int getId() { return id. int salary) { this. String lname. } } We need to define another POJO class corresponding to CERTIFICATE table so that certificate objects can be stored and retrieved into the CERTIFICATE table. this. this. } public void setId( int id ) { this.firstName = fname. } public Map getCertificates() { return certificates.name = name.private int salary.salary = salary. } public String getLastName() { return lastName.lastName = lname. } public int getId() { return id. public class Certificate{ private int id. public Certificate() {} public Certificate(String name) { this. } public void setLastName( String last_name ) { this. public Employee() {} public Employee(String fname. } public void setId( int id ) { this.certificates = certificates.id = id.lastName = last_name. } public void setCertificates( Map certificates ) { this. private String name.id = id. } public String getName() { TUTORIALS POINT Simply Easy Learning .

</meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="name" column="certificate_name" type="string"/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>.return name. The <meta> element is optional element and can be used to create the class description. You are already familiar with most of the mapping detail but let us see all the elements of mapping file once again:     The mapping document is an XML document having <hibernate-mapping> as the root element which contains two <class> elements corresponding to each class.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.name = name. We saved our mapping document in the file Employee.xml. this mapping types will convert from Java to SQL data type.org/dtd/hibernate-mapping-3. } } Define Hibernate Mapping File Let us develop our mapping file which instructs Hibernate how to map the defined classes to the database tables. } public void setName( String name ) { this. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <map name="certificates" cascade="all"> <key column="employee_id"/> <index column="certificate_type" type="string"/> <one-to-many class="Certificate"/> </map> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> <class name="Certificate" table="CERTIFICATE"> <meta attribute="class-description"> This class contains the certificate records.hbm.hbm.hibernate. TUTORIALS POINT Simply Easy Learning . The <class> elements are used to define specific mappings from a Java classes to the database tables. The <map> element will be used to define the rule for the Map used. The type attribute holds the hibernate mapping type.0. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table.xml. The <id> element maps the unique ID attribute in class to the primary key of the database table. <?xml version="1. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail.

as such. /* Let us have a set of certificates for the first employee */ HashMap set = new HashMap().cfg.put("BusinessManagement".Session. set. } TUTORIALS POINT Simply Easy Learning . 5000).configure(). The type attribute holds the hibernate mapping type.buildSessionFactory(). The <map> element is used to set the relationship between Certificate and Employee classes. set. public static void main(String[] args) { try{ factory = new Configuration(). this mapping types will convert from Java to SQL data type.hibernate.println("Failed to create sessionFactory object. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. }catch (Throwable ex) { System. <many-to-one> or <many-to-many> elements based on your requirement.Transaction. Create Application Class Finally. new Certificate("MBA")). org.listEmployees().put("ComputerScience".hibernate. The <one-to-many> element indicates that one Employee object relates to many Certificate objects and. set." + ex).      The <generator> element within the id element is used to automatically generate the primary key values. we will create our application class with the main() method to run the application.*. org.Configuration. set).hibernate. public class ManageEmployee { private static SessionFactory factory. the Certificate object must have a Employee parent associated with it.hibernate. new Certificate("MCA")).SessionFactory. "Kumar". The <property> element is used to map a Java class property to a column in the database table. import import import import import org. /* Update employee's salary records */ ME. org.util. We used the cascade attribute in the <map> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects.err. Set the class attribute of the generator element is set to native to let hibernate pick up either identity. We will use this application to save an Employee record alongwith a list of certificates and then we will apply CRUD operations on that record. The name attribute is set to the defined Mapvariable in the parent class. The <index> element is used to represents the key parts of the key/value map pair. You can use either <one-toone>. import java. table EMPLOYEE. sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database. 4000. org. in our case it is certificates. } ManageEmployee ME = new ManageEmployee(). new Certificate("PMP")).hibernate.put("ProjectManagement".listEmployees(). /* List down all the employees */ ME.updateEmployee(empID. /* List down all the employees */ ME. The key will be stored in the column certificate_type using a type of string. /* Add employee records in the database */ Integer empID = ME.addEmployee("Manoj". throw new ExceptionInInitializerError(ex). The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object ie.HibernateException.

createQuery("FROM Employee"). employeeID = (Integer) session. employee.print("First Name: " + employee.rollback(). Employee employee = new Employee(fname.println("Certificate: " + (((Certificate)ec. for (Iterator iterator1 = employees. HashMap cert){ Session session = factory. Integer employeeID = null.setCertificates(cert). Transaction tx = null.out.update(employee).out.get(Employee.println("Certificate: " + (((Certificate)ec.getFirstName()). try{ tx = session. tx. e. e.class. int salary ){ Session session = factory.getName())).out.close(). System. } return employeeID. } TUTORIALS POINT Simply Easy Learning .rollback(). int salary. } /* Method to list all the employees detail */ public void listEmployees( ){ Session session = factory.out.beginTransaction().next().commit()./* Method to add an employee record in the database */ public Integer addEmployee(String fname. salary). Employee employee = (Employee)session.close(). }catch (HibernateException e) { if (tx!=null) tx.println(" Salary: " + employee. iterator1. session. EmployeeID).printStackTrace(). try{ tx = session.){ Employee employee = (Employee) iterator1.get("ComputerScience")).getCertificates(). System. List employees = session.get("ProjectManagement")).out.getLastName()).setSalary( salary ).getName())).rollback(). }catch (HibernateException e) { if (tx!=null) tx.list(). } tx. System.commit().printStackTrace().getName())). e. }finally { session.beginTransaction().out. Transaction tx = null.iterator().commit(). System. try{ tx = session.println("Certificate: " + (((Certificate)ec.close().openSession().print(" Last Name: " + employee. }finally { session.getSalary()). System.printStackTrace().get("BusinessManagement")). }catch (HibernateException e) { if (tx!=null) tx. employee. Transaction tx = null.beginTransaction().openSession(). Map ec = employee.save(employee).hasNext(). System. tx. } } /* Method to update salary for an employee */ public void updateEmployee(Integer EmployeeID. }finally { session. lname. String lname.openSession().

. session.       Create hibernate. Create ManageEmployee. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.class.java source file as shown above and compile it. Create Employee.. You would get following result on the screen..java source file as shown above and compile it.VARIOUS LOG MESSAGES WILL DISPLAY HERE. }catch (HibernateException e) { if (tx!=null) tx..xml configuration file as explained in configuration chapter. tx.xml mapping file as shown above.get(Employee. they should have following records: mysql> select * from EMPLOYEE. Execute ManageEmployee binary to run the program...} /* Method to delete an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory. Employee employee = (Employee)session. and same time records would be created in EMPLOYEE and CERTIFICATE tables.rollback(). +----+------------+-----------+--------+ | id | first_name | last_name | salary | TUTORIALS POINT Simply Easy Learning .cfg.. e...beginTransaction().hbm.. $java ManageEmployee . Create Certificate. EmployeeID).. First Name: Manoj Certificate: MCA Certificate: MBA Certificate: PMP First Name: Manoj Certificate: MCA Certificate: MBA Certificate: PMP Last Name: Kumar Salary: 4000 Last Name: Kumar Salary: 5000 If you check your EMPLOYEE and CERTIFICATE tables.openSession(). Create Employee.printStackTrace().commit().java source file as shown above and compile it.. try{ tx = session.. } } } Compilation and Execution Here are the steps to compile and run the above mentioned application.delete(employee).close(). Transaction tx = null. }finally { session.

There will be one-to-many relationship between EMPLOYEE and CERTIFICATE objects.util. Define RDBMS Tables Consider a situation where we need to store our employee records in EMPLOYEE table which will have following structure: create table EMPLOYEE ( id INT NOT NULL auto_increment.00 sec) mysql>select * from CERTIFICATE. Further.TreeMap. last_name VARCHAR(20) default NULL. first_name VARCHAR(20) default NULL. TUTORIALS POINT Simply Easy Learning . salary INT default NULL. PRIMARY KEY (id) ). The map is ordered according to the natural ordering of its keys. We will store certificate related information in a separate table which has following structure: create table CERTIFICATE ( id INT NOT NULL auto_increment. assume each employee can have one or more certificate associated with him/her. PRIMARY KEY (id) ). or by a Comparator typically provided at sorted map creation time. A SortedMap is mapped with a <map> element in the mapping table and an ordered map can be initialized with java.00 sec) mysql> Hibernate SortedMap Mappings A SortedMap is a similar java collection as Map that stores elements in key-value pairs and provides a total ordering on its keys. certificate_type VARCHAR(40) default NULL. certificate_name VARCHAR(30) default NULL. +----+--------------------+------------------+-------------+ | id | certificate_type | certificate_name | employee_id | +----+--------------------+------------------+-------------+ | 16 | ProjectManagement | PMP | 60 | | 17 | BusinessManagement | MBA | 60 | | 18 | ComputerScience | MCA | 60 | +----+--------------------+------------------+-------------+ 3 rows in set (0.+----+------------+-----------+--------+ | 60 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0. Duplicate elements are not allowed in the map. employee_id INT default NULL.

TUTORIALS POINT Simply Easy Learning . } public void setLastName( String last_name ) { this.lastName = last_name.util. String lname. } public String getLastName() { return lastName. } public void setCertificates( SortedMap certificates ) { this. int salary) { this. public class Employee { private int id. private String firstName.salary = salary.id = id. import java. } public String getFirstName() { return firstName. } public SortedMap getCertificates() { return certificates. This class should also implement Comparable interface and compareTo method which will be used to sort the key elements of the SortedMap in case you set sort="natural" in your mapping file (see below mapping file). } public void setFirstName( String first_name ) { this. private int salary. } public int getId() { return id.*. } public void setId( int id ) { this.salary = salary. public Employee() {} public Employee(String fname.firstName = fname. } public void setSalary( int salary ) { this.lastName = lname.firstName = first_name. this. } } We need to define another POJO class corresponding to CERTIFICATE table so that certificate objects can be stored and retrieved into the CERTIFICATE table.certificates = certificates. private SortedMap certificates. } public int getSalary() { return salary.Define POJO Classes Let us implement a POJO class Employee which will be used to persist the objects related to EMPLOYEE table and having a collection of certificates in List variable. private String lastName. this.

compareTo(thatCertificate). } public int getId() { return id.0. <?xml version="1. Comparable thatCertificate = that. } else if(thatCertificate == null) { return BEFORE. The <map> element will be used to define the rule for the Map used. private String name.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. } public int compareTo(String that){ final int BEFORE = -1.hibernate. if (that == null) { return BEFORE.id = id.name = name. if(thisCertificate == null) { return AFTER. } else { return thisCertificate. } Comparable thisCertificate = this. final int AFTER = 1.name = name. } public void setId( int id ) { this. } public String getName() { return name.org/dtd/hibernate-mapping-3. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <map name="certificates" cascade="all" sort="MyClass"> <key column="employee_id"/> <index column="certificate_type" type="string"/> TUTORIALS POINT Simply Easy Learning . } public void setName( String name ) { this. } } } Define Hibernate Mapping File Let us develop our mapping file which instructs Hibernate how to map the defined classes to the database tables.public class Certificate implements Comparable <String>{ private int id.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www. public Certificate() {} public Certificate(String name) { this.

Set the class attribute of the generator element is set to native to let hibernate pick up either identity. in our case it is certificates. The type attribute holds the hibernate mapping type.util. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="name" column="certificate_name" type="string"/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>. this mapping types will convert from Java to SQL data type. contains two <class> elements corresponding to each class.  The <index> element is used to represents the key parts of the key/value map pair.  The <one-to-many> element indicates that one Employee object relates to many Certificate objects and.xml. TUTORIALS POINT Simply Easy Learning .  The <meta> element is optional element and can be used to create the class description. You can use either <one-toone>.hbm.<one-to-many class="Certificate"/> </map> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> <class name="Certificate" table="CERTIFICATE"> <meta attribute="class-description"> This class contains the certificate records. The key will be stored in the column certificate_type using a type of string.  The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object ie. We have used a class MyClass which implements java. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table.Comparator. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table.hbm. sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database. import java. You are already familiar with most of the mapping detail but let us see all the elements of mapping file once again:  The mapping document is an XML document having <hibernate-mapping> as the root element which  The <class> elements are used to define specific mappings from a Java classes to the database tables.Comparator. <many-to-one> or <many-to-many> elements based on your requirement.util. the Certificate object must have a Employee parent associated with it. The name attribute is set to the definedSortedMap variable in the parent class.  The <property> element is used to map a Java class property to a column in the database table. We saved our mapping document in the file Employee.xml.  The <id> element maps the unique ID attribute in class to the primary key of the database table.  The <generator> element within the id element is used to automatically generate the primary key values. table EMPLOYEE. Let us do descending sorting of the keys available in the map.  The <map> element is used to set the relationship between Certificate and Employee classes. But we are using a custom comparator classMyClass in our mapping file so we would have to create this class based on our sorting algorithm. this mapping types will convert from Java to SQL data type.Comparator to reverse the sorting order implemented in Certificate class. The sort attribute can be set to natural to have natural sorting or it can be set to a custom class implementingjava. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute. The type attribute holds the hibernate mapping type. If we use sort="natural" setting then we do not need to create a separate class because Certificate class already has implemented Comparable interface and hibernate will use compareTo() method defined in Certificate class to compare SortedMap keys.util. as such. We used the cascade attribute in the <map> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects.

/* Let us have a set of certificates for the first employee */ TreeMap set1 = new TreeMap(). "Kumar".put("BusinessManagement". We will use this application to save few Employee's records alongwith their certificates and then we will apply CRUD operations on those records. } else { return thisCertificate. /* To reverse the sorting order. set2).hibernate. import java. "Kumar". org.configure(). set2.public class MyClass implements Comparator <String>{ public int compare(String o1.put("BusinessManagement". public class ManageEmployee { private static SessionFactory factory. if(thisCertificate == null) { return AFTER * 1.updateEmployee(empID1. we will create our application class with the main() method to run the application. /* Add another employee record in the database */ Integer empID2 = ME. multiple by -1 */ if (o2 == null) { return BEFORE * -1.hibernate. } } } Finally. /* Update employee's salary records */ ME. set1. new Certificate("MBA")). new Certificate("MCA")).addEmployee("Dilip". set1. org. /* List down all the employees */ ME.println("Failed to create sessionFactory object. 5000). set2. TUTORIALS POINT Simply Easy Learning . set1).err. }catch (Throwable ex) { System.listEmployees(). org.addEmployee("Manoj".put("ComputerScience". new Certificate("PMP")).HibernateException.hibernate.hibernate.*. final int AFTER = 1.SessionFactory.Session. Comparable thatCertificate = o2. throw new ExceptionInInitializerError(ex). new Certificate("MCA")). 4000.util. import import import import import org. /* Add employee records in the database */ Integer empID1 = ME. } else if(thatCertificate == null) { return BEFORE * -1.cfg.compareTo(thatCertificate) * -1.hibernate. 3000. public static void main(String[] args) { try{ factory = new Configuration().buildSessionFactory(). org. } ManageEmployee ME = new ManageEmployee().put("ComputerScience".Transaction.put("ProjectManagement". /* Another set of certificates for the second employee */ TreeMap set2 = new TreeMap(). String o2) { final int BEFORE = -1. set1.Configuration." + ex). new Certificate("MBA")). } Comparable thisCertificate = o1.

Certificate> map = employee. Transaction tx = null. TreeMap cert){ Session session = factory. SortedMap<String. tx. }finally { session. } /* Method to list all the employees detail */ public void listEmployees( ){ Session session = factory.class.iterator().Certificate> entry : map. }catch (HibernateException e) { if (tx!=null) tx. for (Iterator iterator1 = employees.next().out. }catch (HibernateException e) { if (tx!=null) tx. int salary. salary).out. System. } return employeeID.close().createQuery("FROM Employee").print(" Last Name: " + employee. /* List down all the employees */ ME.setCertificates(cert). lname./* Delete an employee from the database */ ME. Name: " + (entry. List employees = session. employee.entrySet()){ System.getSalary()).Entry<String. int salary ){ Session session = factory. Integer employeeID = null. e. EmployeeID). Transaction tx = null.hasNext(). } } /* Method to update salary for an employee */ public void updateEmployee(Integer EmployeeID.commit(). employeeID = (Integer) session.printStackTrace(). Transaction tx = null.println(".openSession(). System.print("\tCertificate Type: " + entry. Employee employee = (Employee)session.println(" Salary: " + employee.getLastName()).beginTransaction().commit().beginTransaction(). } } tx.getKey()). try{ tx = session.getFirstName()).deleteEmployee(empID2). String lname.openSession().out.getName()).){ Employee employee = (Employee) iterator1.out.listEmployees(). employee. System.close(). } /* Method to add an employee record in the database */ public Integer addEmployee(String fname. TUTORIALS POINT Simply Easy Learning . Employee employee = new Employee(fname.list().getCertificates().out. try{ tx = session. try{ tx = session.getValue()).beginTransaction(). for(Map.save(employee).print("First Name: " + employee.get(Employee.setSalary( salary ).rollback().printStackTrace().openSession(). e. System.rollback(). iterator1. }finally { session.

}catch (HibernateException e) { if (tx!=null) tx. }finally { session. } } } Compilation and Execution Here are the steps to compile and run the above mentioned application. Name: MCA Certificate Type: BusinessManagement. Execute ManageEmployee binary to run the program. } } /* Method to delete an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory. }finally { session.java source file as shown above and compile it. You can try by changing your mapping file....printStackTrace().cfg.. First Name: Manoj Last Name: Kumar Salary: 4000 Certificate Type: ProjectManagement.get(Employee.session.        Create hibernate.. Create Certificate..java source file as shown above and compile it.xml mapping file as shown above.java source file as shown above and compile it. Employee employee = (Employee)session.. EmployeeID).commit().. $java ManageEmployee .rollback().delete(employee). e. Create MyClass. Create Employee.. You would get following result on the screen.. tx.java source file as shown above and compile it.beginTransaction(). try{ tx = session. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution...close(). Transaction tx = null. e.class.printStackTrace(). Create Employee. Create ManageEmployee.openSession().commit(). You can see certificates type has been sorted in reverse order. Name: PMP Certificate Type: ComputerScience.xml configuration file as explained in configuration chapter. session.update(employee). simply set sort="natural" and execute your program and compare the results.rollback().. tx. and same time records would be created in EMPLOYEE and CERTIFICATE tables.VARIOUS LOG MESSAGES WILL DISPLAY HERE. }catch (HibernateException e) { if (tx!=null) tx.hbm.close(). Name: MBA First Name: Dilip Last Name: Kumar Salary: 3000 TUTORIALS POINT Simply Easy Learning .

Name: MBA If you check your EMPLOYEE and CERTIFICATE tables.00 sec) mysql> Association Mappings The mapping of associations between entity classes and the relationships between tables is the soul of ORM. Following are the four ways in which the cardinality of the relationship between the objects can be expressed.00 sec) mysql> select * from CERTIFICATE. An association mapping can be unidirectional as well as bidirectional. they should have following records: mysql> select * from EMPLOYEE. Name: MCA Certificate Type: BusinessManagement. Name: MBA First Name: Manoj Last Name: Kumar Salary: 5000 Certificate Type: ProjectManagement.Certificate Type: ComputerScience. For example a same address object can be associated with multiple employee objects. Name: MCA Certificate Type: BusinessManagement. Name: PMP Certificate Type: ComputerScience. +----+--------------------+------------------+-------------+ | id | certificate_type | certificate_name | employee_id | +----+--------------------+------------------+-------------+ | 52 | BusinessManagement | MBA | 74 | | 53 | ComputerScience | MCA | 74 | | 54 | ProjectManagement | PMP | 74 | +----+--------------------+------------------+-------------+ 3 rows in set (0. Define RDBMS Tables Consider a situation where we need to store our employee records in EMPLOYEE table which will have following structure: TUTORIALS POINT Simply Easy Learning . +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 74 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0. Mapping type Many-to-One One-to-One One-to-Many Many-to-Many Description Mapping many-to-one relationship using Hibernate Mapping one-to-one relationship using Hibernate Mapping one-to-many relationship using Hibernate Mapping many-to-many relationship using Hibernate Hibernate Many-to-One Mappings A many-to-one association is the most common kind of association where an Object can be associated with multiple objects.

import java. PRIMARY KEY (id) ). } public String getLastName() { return lastName. int salary.firstName = fname. many employee can have same address. Define POJO Classes Let us implement a POJO class Employee which will be used to persist the objects related to EMPLOYEE table and having a variable of Address type. this. Create both the RBDMS tables and keep them ready for the next implementation.*. private Address address.lastName = lname. TUTORIALS POINT Simply Easy Learning . } public int getId() { return id.firstName = first_name. street_name VARCHAR(40) default NULL. address INT NOT NULL. We will store address related information in a separate table which has following structure: create table ADDRESS ( id INT NOT NULL auto_increment. this.create table EMPLOYEE ( id INT NOT NULL auto_increment. } public String getFirstName() { return firstName. private String firstName. } public void setId( int id ) { this. last_name VARCHAR(20) default NULL.address = address. public class Employee{ private int id.salary = salary. } public void setFirstName( String first_name ) { this. state_name VARCHAR(40) default NULL. Further. first_name VARCHAR(20) default NULL. PRIMARY KEY (id) ). public Employee() {} public Employee(String fname. private int salary. String lname. so this association can be presented using many-to-one association. salary INT default NULL. Address address ) { this. private String lastName.id = id.util. zipcode VARCHAR(10) default NULL. city_name VARCHAR(40) default NULL. this.

private String zipcode.city = city.state = state. this. String city. } public String getCity() { return city. } public String getStreet() { return street. } } We need to define another POJO class corresponding to ADDRESS table so that address objects can be stored and retrieved into the ADDRESS table. private String street.} public void setLastName( String last_name ) { this. } public void setSalary( int salary ) { this.street = street. import java. } public int getId() { return id.street = street. } public void setCity( String city ) { this. public Address() {} public Address(String street. this.salary = salary. private String state. } public void setId( int id ) { this. } public Address getAddress() { return address.util. } public String getState() { return state. } public void setAddress( Address address ) { this. } TUTORIALS POINT Simply Easy Learning .address = address.zipcode = zipcode. private String city. } public int getSalary() { return salary. public class Address{ private int id.id = id.city = city.*.lastName = last_name. String zipcode) { this. String state. this. } public void setStreet( String street ) { this.

} public String getZipcode() { return zipcode. We saved our mapping document in the file Employee.hbm.0.hbm. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> <many-to-one name="address" column="address" class="Address" not-null="true"/> </class> <class name="Address" table="ADDRESS"> <meta attribute="class-description"> This class contains the address detail. The <many-to-one> element will be used to define the rule to establish a many-to-one relationship between EMPLOYEE and ADDRESS entities.xml. You are already familiar with most of the mapping detail but let us see all the elements of mapping file once again:  The mapping document is an XML document having <hibernate-mapping> as the root element which contains two <class> elements corresponding to each class.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.zipcode = zipcode. <?xml version="1.hibernate.xml.state = state. } } Define Hibernate Mapping File Let us develop our mapping files which instructs Hibernate how to map the defined classes to the database tables.public void setState( String state ) { this.org/dtd/hibernate-mapping-3. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="street" column="street_name" type="string"/> <property name="city" column="city_name" type="string"/> <property name="state" column="state_name" type="string"/> <property name="zipcode" column="zipcode" type="string"/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>. } public void setZipcode( String zipcode ) { this.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. TUTORIALS POINT Simply Easy Learning .

*.configure(). The <property> element is used to map a Java class property to a column in the database table. /* Add another employee record in the database */ Integer empID2 = ME.hibernate.cfg."AP". Finally. org. org.Configuration. sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. Set the class attribute of the generator element is set to native to let hibernate pick up either identity. address). "Kumar". we will create our application class with the main() method to run the application. 4000.HibernateException. /* List down all the employees */ ME. org.SessionFactory.addEmployee("Manoj". import import import import import org. TUTORIALS POINT Simply Easy Learning .addAddress("Kondapur".deleteEmployee(empID2)." + ex).buildSessionFactory()."532"). The type attribute holds the hibernate mapping type.addEmployee("Dilip". The <meta> element is optional element and can be used to create the class description.println("Failed to create sessionFactory object. /* Update employee's salary records */ ME. /* Let us have one address object */ Address address = ME.Transaction. We will use this application to save few Employee's records alongwith their certificates and then we will apply CRUD operations on those records. throw new ExceptionInInitializerError(ex). import java.hibernate.listEmployees(). this mapping types will convert from Java to SQL data type.updateEmployee(empID1. The type attribute holds the hibernate mapping type. }catch (Throwable ex) { System. address)."Hyderabad". 3000.hibernate. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table.util. The name attribute is set to the defined variable in the parent class.hibernate.listEmployees(). 5000). this mapping types will convert from Java to SQL data type. /* Add employee records in the database */ Integer empID1 = ME. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute. in our case it is address. "Kumar". public class ManageEmployee { private static SessionFactory factory.      The <class> elements are used to define specific mappings from a Java classes to the database tables. /* Delete an employee from the database */ ME. The <many-to-one> element is used to set the relationship between EMPLOYEE and ADDRESS entities. } ManageEmployee ME = new ManageEmployee(). org.Session.hibernate. The <generator> element within the id element is used to automatically generate the primary key values. /* List down all the employees */ ME. The column attribute is used to set the column name in the parent table EMPLOYEE.err. public static void main(String[] args) { try{ factory = new Configuration(). The <id> element maps the unique ID attribute in class to the primary key of the database table.

System.out. Transaction tx = null.println("\tZipcode: " + add.out.getSalary()). address).rollback().println("\tState: " + add. }finally { session.println("\tStreet: " + add. address = new Address(street. }catch (HibernateException e) { if (tx!=null) tx. String city.getFirstName()). e.out.save(address).iterator(). iterator.openSession().out. Employee employee = new Employee(fname.printStackTrace(). }finally { TUTORIALS POINT Simply Easy Learning . Address address){ Session session = factory.commit().getZipcode()).out. int salary. }catch (HibernateException e) { if (tx!=null) tx. } return employeeID. Address add = employee. try{ tx = session. }finally { session.beginTransaction().} /* Method to add an address record in the database */ public Address addAddress(String street.printStackTrace().save(employee).beginTransaction(). System.openSession().commit(). addressID = (Integer) session.getState()).beginTransaction().close(). List employees = session. for (Iterator iterator = employees. try{ tx = session. String state. } /* Method to add an employee record in the database */ public Integer addEmployee(String fname.hasNext().println(" Salary: " + employee. Integer addressID = null. System. tx. } /* Method to list all the employees detail */ public void listEmployees( ){ Session session = factory. String zipcode) { Session session = factory. }catch (HibernateException e) { if (tx!=null) tx.){ Employee employee = (Employee) iterator.printStackTrace(). try{ tx = session. Transaction tx = null. System.out.rollback(). System.openSession(). zipcode).print("First Name: " + employee. String lname.print(" Last Name: " + employee.out.getCity()). tx. Address address = null.createQuery("FROM Employee").list().commit(). city. state. e. lname.getAddress().println("\tCity: " + add. } return address.println("Address "). } tx. Transaction tx = null.getStreet()). System. System.getLastName()).rollback().out.close(). Integer employeeID = null. System. salary. e.next(). employeeID = (Integer) session.

.delete(employee).class.. EmployeeID).commit().get(Employee. e. EmployeeID).rollback(). } } /* Method to update salary for an employee */ public void updateEmployee(Integer EmployeeID. TUTORIALS POINT Simply Easy Learning ..xml configuration file as explained in configuration chapter.commit().printStackTrace(). Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.       Create hibernate. Execute ManageEmployee binary to run the program. Employee employee = (Employee)session..VARIOUS LOG MESSAGES WILL DISPLAY HERE.. $java ManageEmployee .openSession().. tx. e. try{ tx = session.. Create Employee.close().setSalary( salary ).close(). employee. }catch (HibernateException e) { if (tx!=null) tx.update(employee). session.. Transaction tx = null. Employee employee = (Employee)session.cfg.java source file as shown above and compile it...get(Employee. }finally { session. and same time records would be created in EMPLOYEE and ADDRESS tables. Create ManageEmployee.rollback(). Transaction tx = null.xml mapping file as shown above. } } } Compilation and Execution Here are the steps to compile and run the above mentioned application. }finally { session.hbm. You would get following result on the screen. try{ tx = session.close(). }catch (HibernateException e) { if (tx!=null) tx.session.class.beginTransaction(). session. Create Employee.. } } /* Method to delete an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory.java source file as shown above and compile it.. tx. Create Address.printStackTrace().java source file as shown above and compile it.openSession(). int salary ){ Session session = factory..beginTransaction().

salary INT default NULL. they should have following records: mysql> select * from EMPLOYEE. last_name VARCHAR(20) default NULL.00 sec) mysql> Hibernate One-to-One Mappings A one-to-one association is similar to many-to-one association with a difference that the column will be set as unique. For example an address object can be associated with a single employee object.00 sec) mysql> select * from ADDRESS. +----+-------------+-----------+------------+---------+ | id | street_name | city_name | state_name | zipcode | +----+-------------+-----------+------------+---------+ | 1 | Kondapur | Hyderabad | AP | 532 | +----+-------------+-----------+------------+---------+ 1 row in set (0.First Name: Manoj Last Name: Kumar Address Street: Kondapur City: Hyderabad State: AP Zipcode: 532 First Name: Dilip Last Name: Kumar Address Street: Kondapur City: Hyderabad State: AP Zipcode: 532 First Name: Manoj Last Name: Kumar Address Street: Kondapur City: Hyderabad State: AP Zipcode: 532 Salary: 4000 Salary: 3000 Salary: 5000 If you check your EMPLOYEE and CERTIFICATE tables. Define RDBMS Tables Consider a situation where we need to store our employee records in EMPLOYEE table which will have following structure: create table EMPLOYEE ( id INT NOT NULL auto_increment. +----+------------+-----------+--------+---------+ | id | first_name | last_name | salary | address | +----+------------+-----------+--------+---------+ | 1 | Manoj | Kumar | 5000 | 5 | +----+------------+-----------+--------+---------+ 1 row in set (0. first_name VARCHAR(20) default NULL. TUTORIALS POINT Simply Easy Learning .

} public String getFirstName() { return firstName. PRIMARY KEY (id) ).address INT NOT NULL. so this association can be presented using one-to-one association. public Employee() {} public Employee(String fname. city_name VARCHAR(40) default NULL. Address address ) { this. } public int getId() { return id. assuming that an address can be associated a single employee only.lastName = lname. } public void setLastName( String last_name ) { this. this. public class Employee{ private int id. Define POJO Classes Let us implement a POJO class Employee which will be used to persist the objects related to EMPLOYEE table and having a variable of Address type. private String firstName.firstName = first_name. } TUTORIALS POINT Simply Easy Learning . private int salary. this. import java. } public String getLastName() { return lastName. Further. private String lastName. this. int salary.firstName = fname. String lname. Create both the RBDMS tables and keep them ready for the next implementation.salary = salary. street_name VARCHAR(40) default NULL.util.*.lastName = last_name. zipcode VARCHAR(10) default NULL. private Address address. } public void setFirstName( String first_name ) { this.id = id. We will store address related information in a separate table which has following structure: create table ADDRESS ( id INT NOT NULL auto_increment. } public void setId( int id ) { this.address = address. PRIMARY KEY (id) ). state_name VARCHAR(40) default NULL.

} public void setAddress( Address address ) { this. this.city = city. } public String getState() { return state. } public int getId() { return id. } public String getCity() { return city. } public void setState( String state ) { this.address = address.state = state. } public void setSalary( int salary ) { this. public class Address{ private int id. this.zipcode = zipcode. this. String city.street = street. private String state. } public Address getAddress() { return address. } } We need to define another POJO class corresponding to ADDRESS table so that address objects can be stored and retrieved into the ADDRESS table. private String city. public Address() {} public Address(String street.id = id.state = state. private String zipcode. String zipcode) { this.salary = salary. import java. } public void setId( int id ) { this.util. private String street.street = street. } public String getZipcode() { TUTORIALS POINT Simply Easy Learning . } public void setStreet( String street ) { this.*. } public String getStreet() { return street.public int getSalary() { return salary.city = city. String state. } public void setCity( String city ) { this.

TUTORIALS POINT Simply Easy Learning . The <many-to-one> element will be used to define the rule to establish a one-to-one relationship between EMPLOYEE and ADDRESS entities but column attribute will be set to uniqueconstraint and rest of the mapping file will remain as it was in case of many-to-one association.xml. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="street" column="street_name" type="string"/> <property name="city" column="city_name" type="string"/> <property name="state" column="state_name" type="string"/> <property name="zipcode" column="zipcode" type="string"/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>.zipcode = zipcode.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hbm.0. You are already familiar with most of the mapping detail but let us see all the elements of mapping file once again:  The mapping document is an XML document having <hibernate-mapping> as the root element which  The <class> elements are used to define specific mappings from a Java classes to the database tables.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. <?xml version="1.org/dtd/hibernate-mapping-3.return zipcode. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute. } public void setZipcode( String zipcode ) { this.  The <id> element maps the unique ID attribute in class to the primary key of the database table. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> <many-to-one name="address" column="address" unique="true" class="Address" not-null="true"/> </class> <class name="Address" table="ADDRESS"> <meta attribute="class-description"> This class contains the address detail. } } Define Hibernate Mapping File Let us develop our mapping files which instructs Hibernate how to map the defined classes to the database tables.hibernate.  The <meta> element is optional element and can be used to create the class description.hbm. We saved our mapping document in the file Employee.xml. The name attribute of the id element refers to the property in the class and the column attribute refers to the contains two <class> elements corresponding to each class.

4000.err. String zipcode) { Session session = factory. The type attribute holds the hibernate mapping type. /* Add employee records in the database */ Integer empID1 = ME.listEmployees(). The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. throw new ExceptionInInitializerError(ex). The type attribute holds the hibernate mapping type.cfg. import import import import import org.*.Transaction.addEmployee("Dilip". } /* Method to add an address record in the database */ public Address addAddress(String street." + ex). TUTORIALS POINT Simply Easy Learning . Transaction tx = null. }catch (Throwable ex) { System.Session.  The <generator> element within the id element is used to automatically generate the primary key values.HibernateException.util.SessionFactory. org. Finally. String state. Set the class attribute of the generator element is set to native to let hibernate pick up either identity.hibernate. address1). public static void main(String[] args) { try{ factory = new Configuration(). /* List down all the employees */ ME. import java.hibernate. /* Add another employee record in the database */ Integer empID2 = ME.  The <property> element is used to map a Java class property to a column in the database table. /* List down all the employees */ ME. public class ManageEmployee { private static SessionFactory factory. /* Let us have one address object */ Address address1 = ME.hibernate. String city.hibernate.listEmployees(). this mapping types will convert from Java to SQL data type.hibernate. 5000). We will use this application to save few Employee's records alongwith their certificates and then we will apply CRUD operations on those records."Ambehta".column in the database table.Configuration.openSession(). in our case it is address. /* Update employee's salary records */ ME. org. address2). sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database."532"). The column attribute is used to set the column name in the parent table EMPLOYEE which is set to unique so that only one Employee object can be associated with an address object. 3000. org. } ManageEmployee ME = new ManageEmployee().addAddress("Kondapur".buildSessionFactory().addAddress("Saharanpur".println("Failed to create sessionFactory object."111")."Hyderabad". this mapping types will convert from Java to SQL data type. /* Let us have another address object */ Address address2 = ME. "Kumar". we will create our application class with the main() method to run the application. The name attribute is set to the defined variable in the parent class.configure()."UP". org."AP". "Kumar".addEmployee("Manoj".updateEmployee(empID1.  The <many-to-one> element is used to set the relationship between EMPLOYEE and ADDRESS entities.

} /* Method to list all the employees detail */ public void listEmployees( ){ Session session = factory. Employee employee = new Employee(fname. salary. zipcode). }finally { session.print("First Name: " + employee.out.println("\tCity: " + add.getSalary()).println("\tState: " + add. Address address){ Session session = factory. }catch (HibernateException e) { if (tx!=null) tx.list().out. Integer employeeID = null. } tx.getStreet()). Address add = employee.commit(). } } /* Method to update salary for an employee */ public void updateEmployee(Integer EmployeeID. } return address.getFirstName()).print(" Last Name: " + employee. city. System. tx. TUTORIALS POINT Simply Easy Learning .Integer addressID = null. } return employeeID.printStackTrace().println("\tZipcode: " + add.){ Employee employee = (Employee) iterator.beginTransaction(). System. int salary.rollback().out.openSession(). }finally { session. }finally { session.getCity()). iterator. Address address = null. for (Iterator iterator = employees. e.close().hasNext(). Transaction tx = null.openSession().next().openSession().out. System. List employees = session. System. System. employeeID = (Integer) session.getLastName()). e.println("Address ").out. } /* Method to add an employee record in the database */ public Integer addEmployee(String fname.save(address). try{ tx = session.printStackTrace(). }catch (HibernateException e) { if (tx!=null) tx.createQuery("FROM Employee").println(" Salary: " + employee. int salary ){ Session session = factory.beginTransaction().out. lname.println("\tStreet: " + add. Transaction tx = null.getZipcode()). state. System.printStackTrace(). System. System. }catch (HibernateException e) { if (tx!=null) tx.commit().out. try{ tx = session.beginTransaction(). address = new Address(street.close(). try{ tx = session. tx.rollback().close().getState()). Transaction tx = null.iterator().out.save(employee).rollback(). address). addressID = (Integer) session.getAddress().commit(). String lname. e.

java source file as shown above and compile it.try{ tx = session. }catch (HibernateException e) { if (tx!=null) tx. You would get following result on the screen. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.rollback(). }finally { session.close()...setSalary( salary )...cfg....       Create hibernate..VARIOUS LOG MESSAGES WILL DISPLAY HERE. session. Employee employee = (Employee)session. EmployeeID)..beginTransaction(). Create Employee. $java ManageEmployee ... Execute ManageEmployee binary to run the program.hbm. Create Employee.xml mapping file as shown above.printStackTrace(). and same time records would be created in EMPLOYEE and ADDRESS tables. First Name: Manoj Last Name: Address Street: Kondapur City: Hyderabad State: AP Zipcode: 532 First Name: Dilip Last Name: Address Street: Saharanpur City: Ambehta State: UP Zipcode: 111 First Name: Manoj Last Name: Address Street: Kondapur City: Hyderabad State: AP Zipcode: 532 First Name: Dilip Last Name: Address Street: Saharanpur Kumar Salary: 4000 Kumar Salary: 3000 Kumar Salary: 5000 Kumar Salary: 3000 TUTORIALS POINT Simply Easy Learning . } } } Compilation and Execution Here are the steps to compile and run the above mentioned application..java source file as shown above and compile it.update(employee).commit(). Create ManageEmployee.java source file as shown above and compile it. tx.class.get(Employee..xml configuration file as explained in configuration chapter. employee. e. Create Address.

Further. Define RDBMS Tables Consider a situation where we need to store our employee records in EMPLOYEE table which will have following structure: create table EMPLOYEE ( id INT NOT NULL auto_increment. first_name VARCHAR(20) default NULL. We already have seen how to map Set collection in hibernate.00 sec) mysql> select * from ADDRESS. You can use Set collection in your class when there is no duplicate element required in the collection. So we will store certificate related information in a separate table which has following structure: create table CERTIFICATE ( id INT NOT NULL auto_increment. they should have following records: mysql> select * from EMPLOYEE.HashSet. TUTORIALS POINT Simply Easy Learning . salary INT default NULL. A Set is mapped with a <set> element in the mapping table and initialized with java. certificate_name VARCHAR(30) default NULL.util. assume each employee can have one or more certificate associated with him/her. PRIMARY KEY (id) ).00 sec) mysql> Hibernate One-to-Many Mappings A One-to-Many mapping can be implemented using a Set java collection that does not contain any duplicate element.City: Ambehta State: UP Zipcode: 111 If you check your EMPLOYEE and CERTIFICATE tables. +----+------------+-----------+--------+---------+ | id | first_name | last_name | salary | address | +----+------------+-----------+--------+---------+ | 7 | Manoj | Kumar | 5000 | 5 | | 8 | Dilip | Kumar | 3000 | 6 | +----+------------+-----------+--------+---------+ 2 rows in set (0. +----+-------------+-----------+------------+---------+ | id | street_name | city_name | state_name | zipcode | +----+-------------+-----------+------------+---------+ | 5 | Kondapur | Hyderabad | AP | 532 | | 6 | Saharanpur | Ambehta | UP | 111 | +----+-------------+-----------+------------+---------+ 2 rows in set (0. employee_id INT default NULL. last_name VARCHAR(20) default NULL. so if you already learned Set mapping then you are all set to go with one-to-many mapping.

} } Now let us define another POJO class corresponding to CERTIFICATE table so that certificate objects can be stored and retrieved into the CERTIFICATE table. this. public Employee() {} public Employee(String fname. public class Employee { private int id. } public void setId( int id ) { this.lastName = lname. } public Set getCertificates() { return certificates. TUTORIALS POINT Simply Easy Learning .firstName = fname.salary = salary. import java. int salary) { this. private String firstName.salary = salary. String lname. } public void setCertificates( Set certificates ) { this. } public String getFirstName() { return firstName. } public String getLastName() { return lastName. private String lastName. private int salary. private Set certificates.PRIMARY KEY (id) ). } public int getId() { return id. This class should also implement both the equals() and hashCode() methods so that Java can determine whether any two elements/objects are identical.lastName = last_name.id = id. } public int getSalary() { return salary. } public void setSalary( int salary ) { this. this.firstName = first_name. } public void setLastName( String last_name ) { this.util.certificates = certificates. There will be one-to-many relationship between EMPLOYEE and CERTIFICATE objects: Define POJO Classes Let us implement our POJO class Employee which will be used to persist the objects related to EMPLOYEE table and having a collection of certificates in Set variable.*. } public void setFirstName( String first_name ) { this.

<?xml version="1.getClass(). } } Define Hibernate Mapping File Let us develop our mapping file which instructs Hibernate how to map the defined classes to the database tables. TUTORIALS POINT Simply Easy Learning .name = name. } return false. } public boolean equals(Object obj) { if (obj == null) return false.hibernate. private String name. Certificate obj2 = (Certificate)obj.0.id == obj2. } public void setId( int id ) { this.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail.getClass())) return false.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www. if((this. public Certificate() {} public Certificate(String name) { this. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <set name="certificates" cascade="all"> <key column="employee_id"/> <one-to-many class="Certificate"/> </set> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> <class name="Certificate" table="CERTIFICATE"> <meta attribute="class-description"> This class contains the certificate records.equals(obj2. } public void setName( String name ) { this.name = name.public class Certificate { private int id. } public String getName() { return name.equals(obj. } public int hashCode() { int tmp = 0.id = id.getId()) && (this.name.getName()))) { return true. } public int getId() { return id.hashCode(). if (!this.org/dtd/hibernate-mapping-3. return tmp. tmp = ( id + name ).

buildSessionFactory(). org.hibernate. The <meta> element is optional element and can be used to create the class description. }catch (Throwable ex) { TUTORIALS POINT Simply Easy Learning . The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.xml. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. Create Application Class Finally. Set the class attribute of the generator element is set to native to let hibernate pick up either identity.HibernateException.hibernate. For each set variable.Session.hibernate.util.Configuration. import java. We used the cascade attribute in the <set> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects.hbm. The <set> element sets the relationship between Certificate and Employee classes. The type attribute holds the hibernate mapping type. this mapping types will convert from Java to SQL data type. org. public static void main(String[] args) { try{ factory = new Configuration(). You are already familiar with most of the mapping detail but let us see all the elements of mapping file once again:          The mapping document is an XML document having <hibernate-mapping> as the root element which contains two <class> elements corresponding to each class. The name attribute is set to the defined Set variable in the parent class. The <one-to-many> element indicates that one Employee object relates to many Certificate objects. We saved our mapping document in the file Employee. The type attribute holds the hibernate mapping type. sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database. The <class> elements are used to define specific mappings from a Java classes to the database tables. we need to define a separate set element in the mapping file. The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object ie. import import import import import org.hbm. in our case it is certificates.xml. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table.*. table EMPLOYEE.hibernate.configure(). org.hibernate.</meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="name" column="certificate_name" type="string"/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>. this mapping types will convert from Java to SQL data type.SessionFactory. We will use this application to save few Employee's records alongwith their certificates and then we will apply CRUD operations on those records. public class ManageEmployee { private static SessionFactory factory. we will create our application class with the main() method to run the application. org. The <generator> element within the id element is used to automatically generate the primary key values.cfg. The <id> element maps the unique ID attribute in class to the primary key of the database table.Transaction. The <property> element is used to map a Java class property to a column in the database table.

try{ tx = session.println("Failed to create sessionFactory object. set1).printStackTrace().add(new Certificate("BCA")).createQuery("FROM Employee").openSession(). employeeID = (Integer) session.listEmployees(). employee. TUTORIALS POINT Simply Easy Learning . set2).addEmployee("Manoj". Integer employeeID = null.list().updateEmployee(empID1.err. 3000.listEmployees().deleteEmployee(empID2). Employee employee = new Employee(fname.beginTransaction(). } /* Method to list all the employees detail */ public void listEmployees( ){ Session session = factory.save(employee). set1." + ex).setCertificates(cert).addEmployee("Dilip". } return employeeID.){ Employee employee = (Employee) iterator1. "Kumar". */ /* Add another employee record in the database */ Integer empID2 = ME.out. throw new ExceptionInInitializerError(ex). int salary. System. System. List employees = session. /* Delete an employee from the database */ ME. /* Update employee's salary records */ ME.next(). "Kumar". /* List down all the employees */ ME. tx. String lname. 4000. /* List down all the employees */ ME. try{ tx = session.rollback().commit(). iterator1. salary). 5000). /* Let us have a set of certificates for the first employee HashSet set1 = new HashSet().openSession().print("First Name: " + employee.add(new Certificate("BA")). set2.close(). */ /* Add employee records in the database */ Integer empID1 = ME.getLastName()). set1.out. lname. } /* Method to add an employee record in the database */ public Integer addEmployee(String fname. Set cert){ Session session = factory. set2. Transaction tx = null. for (Iterator iterator1 = employees.add(new Certificate("MBA")).getFirstName()).add(new Certificate("MCA")).iterator(). Transaction tx = null. } ManageEmployee ME = new ManageEmployee().add(new Certificate("PMP")).print(" Last Name: " + employee.hasNext(). }finally { session.System. set1. e. /* Another set of certificates for the second employee HashSet set2 = new HashSet().beginTransaction(). }catch (HibernateException e) { if (tx!=null) tx.

close(). Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.    Create hibernate.printStackTrace(). } } /* Method to delete an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory.get(Employee.cfg.get(Employee.rollback().class.close(). } } /* Method to update salary for an employee */ public void updateEmployee(Integer EmployeeID.hbm.next().xml configuration file as explained in configuration chapter. for (Iterator iterator2 = certificates.){ Certificate certName = (Certificate) iterator2. Employee employee = (Employee)session. EmployeeID).beginTransaction(). System. Create Employee.System.hasNext().println(" Salary: " + employee.commit(). }catch (HibernateException e) { if (tx!=null) tx.update(employee).out. TUTORIALS POINT Simply Easy Learning .printStackTrace().java source file as shown above and compile it. try{ tx = session.delete(employee). Set certificates = employee. e. iterator2.rollback(). }finally { session. EmployeeID).printStackTrace(). e.commit(). Transaction tx = null. tx. e. }finally { session. }finally { session.commit().close().getSalary()). Create Employee.class. session. }catch (HibernateException e) { if (tx!=null) tx. } } } Compilation and Execution Here are the steps to compile and run the above mentioned application.openSession().getName()).setSalary( salary ).println("Certificate: " + certName. session. tx.getCertificates().xml mapping file as shown above. Employee employee = (Employee)session.iterator().openSession().out. try{ tx = session.beginTransaction(). }catch (HibernateException e) { if (tx!=null) tx. employee. } } tx. int salary ){ Session session = factory.rollback(). Transaction tx = null.

.00 sec) mysql> Hibernate Many-to-Many Mappings A Many-to-Many mapping can be implemented using a Set java collection that does not contain any duplicate element..... You would get following result on the screen. and same time records would be created in EMPLOYEE and CERTIFICATE tables.java source file as shown above and compile it. Create ManageEmployee. A Set is mapped with a <set> element in the mapping table and initialized with java. $java ManageEmployee .java source file as shown above and compile it. +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0. You can use Set collection in your class when there is no duplicate element required in the collection. +----+------------------+-------------+ | id | certificate_name | employee_id | +----+------------------+-------------+ | 1 | MBA | 1 | | 2 | PMP | 1 | | 3 | MCA | 1 | +----+------------------+-------------+ 3 rows in set (0...... First Name: Manoj Certificate: MBA Certificate: PMP Certificate: MCA First Name: Dilip Certificate: BCA Certificate: BA First Name: Manoj Certificate: MBA Certificate: PMP Certificate: MCA Last Name: Kumar Salary: 4000 Last Name: Kumar Last Name: Kumar Salary: 3000 Salary: 5000 If you check your EMPLOYEE and CERTIFICATE tables. they should have following records: mysql> select * from employee.   Create Certificate.util..VARIOUS LOG MESSAGES WILL DISPLAY HERE... Execute ManageEmployee binary to run the program. TUTORIALS POINT Simply Easy Learning .HashSet. so if you already learned Set mapping then you are all set to go with many-to-many mapping. We already have seen how to map Set collection in hibernate.00 sec) mysql> select * from certificate.

salary = salary. } TUTORIALS POINT Simply Easy Learning . PRIMARY KEY (employee_id. import java.certificate_id) ). private Set certificates.Define RDBMS Tables Consider a situation where we need to store our employee records in EMPLOYEE table which will have following structure: create table EMPLOYEE ( id INT NOT NULL auto_increment. String lname.id = id. private int salary. public Employee() {} public Employee(String fname. certificate_id INT NOT NULL. We will store certificate related information in a separate table which has following structure: create table CERTIFICATE ( id INT NOT NULL auto_increment. assume each employee can have one or more certificate associated with him/her and a similar certificate can be associated with more than one employee. } public int getId() { return id.firstName = fname.util. salary INT default NULL. } public String getFirstName() { return firstName. Further. } public void setId( int id ) { this. this. we would have to introduce one more intermediate table having Employee ID and Certificate ID as follows: create table EMP_CERT ( employee_id INT NOT NULL. certificate_name VARCHAR(30) default NULL.lastName = lname. PRIMARY KEY (id) ).*. first_name VARCHAR(20) default NULL. last_name VARCHAR(20) default NULL. Define POJO Classes Let us implement our POJO class Employee which will be used to persist the objects related to EMPLOYEE table and having a collection of certificates in Set variable. Now to implement many-to-many relationship between EMPLOYEE and CERTIFICATE objects. private String firstName. PRIMARY KEY (id) ). public class Employee { private int id. this. int salary) { this. private String lastName.

} public Set getCertificates() { return certificates.hashCode(). if((this.lastName = last_name. if (!this. return tmp. This class should also implement both the equals() and hashCode() methods so that Java can determine whether any two elements/objects are identical.getClass(). } public int hashCode() { int tmp = 0. } public boolean equals(Object obj) { if (obj == null) return false. } public String getName() { return name.certificates = certificates. } public int getSalary() { return salary.id = id.getClass())) return false. public Certificate() {} public Certificate(String name) { this.equals(obj2.getId()) && (this. } return false. } public void setLastName( String last_name ) { this.salary = salary. } } Now let us define another POJO class corresponding to CERTIFICATE table so that certificate objects can be stored and retrieved into the CERTIFICATE table. tmp = ( id + name ).name = name. } public int getId() { return id. } public void setId( int id ) { this. } public void setCertificates( Set certificates ) { this. public class Certificate { private int id.public void setFirstName( String first_name ) { this.equals(obj.id == obj2. } public void setSalary( int salary ) { this. } public void setName( String name ) { this. } } TUTORIALS POINT Simply Easy Learning .firstName = first_name. private String name.name = name.getName()))) { return true. Certificate obj2 = (Certificate)obj. } public String getLastName() { return lastName.name.

sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database.0. this mapping types will convert from Java to SQL data type. The <id> element maps the unique ID attribute in class to the primary key of the database table. We saved our mapping document in the file Employee. We set cascade attribute to save-update to tell Hibernate to persist the Certificate objects for SAVE i.e. The <set> element will be used to define the rule for many-to-many relationship. this mapping types will convert from Java to SQL data type. The type attribute holds the hibernate mapping type.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. The   Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute. The <meta> element is optional element and can be used to create the class description. <?xml version="1.hibernate. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. CREATE and UPDATE contains two <class> elements corresponding to each class. The <generator> element within the id element is used to automatically generate the primary key values.hbm. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <set name="certificates" cascade="save-update" table="EMP_CERT"> <key column="employee_id"/> <many-to-many column="certificate_id" class="Certificate"/> </set> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> <class name="Certificate" table="CERTIFICATE"> <meta attribute="class-description"> This class contains the certificate records. The <set> element sets the relationship between Certificate and Employee classes. The <property> element is used to map a Java class property to a column in the database table.hbm.    TUTORIALS POINT Simply Easy Learning .Define Hibernate Mapping File Let us develop our mapping file which instructs Hibernate how to map the defined classes to the database tables.xml. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="name" column="certificate_name" type="string"/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.org/dtd/hibernate-mapping-3. You are already familiar with most of the mapping detail but let us see all the elements of mapping file once again:  The mapping document is an XML document having <hibernate-mapping> as the root element which  The <class> elements are used to define specific mappings from a Java classes to the database tables. Set the class attribute of the generator element is set to native to let hibernate pick up either identity.xml.

certificates. certificates. Set cert){ Session session = factory.add(new Certificate("MBA")). We will use this application to save few Employee's records alongwith their certificates and then we will apply CRUD operations on those records. int salary.HibernateException. TUTORIALS POINT Simply Easy Learning .util.cfg. in our case it is certificates. /* List down all the employees */ ME. certificates). /* List down all the employees */ ME. import import import import import org. org.addEmployee("Manoj". throw new ExceptionInInitializerError(ex). we will create our application class with the main() method to run the application.hibernate. /* Add another employee record in the database */ Integer empID2 = ME.listEmployees(). org. org.Configuration. 5000). public class ManageEmployee { private static SessionFactory factory.buildSessionFactory(). /* Update employee's salary records */ ME.hibernate. Create Application Class Finally.add(new Certificate("PMP")).SessionFactory.operations at the same time as the Employee objects.  The <key> element is the column in the EMP_CERT table that holds the foreign key to the parent object ie. certificates).updateEmployee(empID1. /* Delete an employee from the database */ ME.addEmployee("Dilip". } /* Method to add an employee record in the database */ public Integer addEmployee(String fname.configure(). /* Add employee records in the database */ Integer empID1 = ME. certificates. The name attribute is set to the defined Set variable in the parent class. public static void main(String[] args) { try{ factory = new Configuration().listEmployees().add(new Certificate("MCA")). "Kumar".hibernate.Session." + ex).err.*. org. table EMPLOYEE and links to the certification_id in the CERTIFICATE table. Here we used nameattribute to set the intermediate table name to EMP_CERT. Integer employeeID = null.Transaction.  The <many-to-many> element indicates that one Employee object relates to many Certificate objects and column attributes are used to link intermediate EMP_CERT. we need to define a separate set element in the mapping file. 3000. 4000. } ManageEmployee ME = new ManageEmployee().hibernate.hibernate.println("Failed to create sessionFactory object. }catch (Throwable ex) { System. String lname.openSession(). For each set variable. "Kumar". import java.deleteEmployee(empID2). Transaction tx = null. /* Let us have a set of certificates for the first employee */ HashSet certificates = new HashSet().

next(). List employees = session.rollback().){ Certificate certName = (Certificate) iterator2. }catch (HibernateException e) { if (tx!=null) tx.getCertificates(). }finally { session. iterator1.getName()).out. System. lname. for (Iterator iterator1 = employees. EmployeeID). Employee employee = new Employee(fname.commit(). Employee employee = (Employee)session. try{ tx = session.getLastName()).getSalary()). employee. System.out.openSession(). System. Transaction tx = null.print(" Last Name: " + employee.out.beginTransaction().print("First Name: " + employee.rollback().setCertificates(cert).update(employee).list().save(employee). iterator2.printStackTrace().println(" Salary: " + employee. }finally { session.printStackTrace().get(Employee. e.close().getFirstName()). Transaction tx = null. try{ tx = session. for (Iterator iterator2 = certificates.beginTransaction(). Transaction tx = null. int salary ){ Session session = factory. }catch (HibernateException e) { if (tx!=null) tx.openSession().beginTransaction().hasNext().class.commit().rollback().setSalary( salary ). System. salary). } } /* Method to delete an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory. employee.println("Certificate: " + certName. e. tx.out.iterator().next(). session.hasNext(). } } tx. try{ tx = session. } } /* Method to update salary for an employee */ public void updateEmployee(Integer EmployeeID.openSession(). Employee employee = TUTORIALS POINT Simply Easy Learning . } /* Method to list all the employees detail */ public void listEmployees( ){ Session session = factory.createQuery("FROM Employee").iterator(). e.commit(). }finally { session.try{ tx = session. } return employeeID. employeeID = (Integer) session.beginTransaction().close(). Set certificates = employee. tx.){ Employee employee = (Employee) iterator1.printStackTrace(). }catch (HibernateException e) { if (tx!=null) tx.close().

}catch (HibernateException e) { if (tx!=null) tx.hbm.. and same time records would be created in EMPLOYEE. EMP_CERT and CERTIFICATE tables.get(Employee.xml configuration file as explained in configuration chapter..VARIOUS LOG MESSAGES WILL DISPLAY HERE.java source file as shown above and compile it.xml mapping file as shown above.delete(employee). EMP_CERT and CERTIFICATE tables..java source file as shown above and compile it.java source file as shown above and compile it. +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 22 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0. Create Employee.00 sec) TUTORIALS POINT Simply Easy Learning ..commit(). EmployeeID).rollback(). tx..close().. Create Employee.. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.class. session. } } } Compilation and Execution Here are the steps to compile and run the above mentioned application.(Employee)session. Execute ManageEmployee binary to run the program... Create Certificate.printStackTrace(). First Name: Manoj Certificate: MBA Certificate: PMP Certificate: MCA First Name: Dilip Certificate: MBA Certificate: PMP Certificate: MCA First Name: Manoj Certificate: MBA Certificate: PMP Certificate: MCA Last Name: Kumar Salary: 4000 Last Name: Kumar Salary: 3000 Last Name: Kumar Salary: 5000 If you check your EMPLOYEE. $java ManageEmployee .       Create hibernate.cfg.. they should have following records: mysql> select * from EMPLOYEE.. }finally { session. e. Create ManageEmployee. You would get following result on the screen...

mysql> select * from CERTIFICATE; +----+------------------+ | id | certificate_name | +----+------------------+ | 4 | MBA | | 5 | PMP | | 6 | MCA | +----+------------------+ 3 rows in set (0.00 sec) mysql> select * from EMP_CERT; +-------------+----------------+ | employee_id | certificate_id | +-------------+----------------+ | 22 | 4 | | 22 | 5 | | 22 | 6 | +-------------+----------------+ 3 rows in set (0.00 sec) mysql>

Component Mappings
It is very much possible that an Entity class can have a reference to another class as a member variable. If the referred class does not have it's own life cycle and completely depends on the life cycle of the owning entity class, then the referred class hence therefore is called as the Component class. The mapping of Collection of Components is also possible in a similar way just as the mapping of regular Collections with minor configuration differences. We will see these two mappings in detail with examples. Mapping type Component Mappings Description Mapping for a class having a reference to another class as a member variable.

Hibernate Component Mappings
A Component mapping is a mapping for a class having a reference to another class as a member variable. We have seen such mapping while having two tables and using <set> element in the mapping file. Now we will use <component> element in the mapping file and a single table would be used to keep the attributes contained inside the class variable.

Define RDBMS Tables
Consider a situation where we need to store our employee records in EMPLOYEE table which will have following structure: create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id)

TUTORIALS POINT Simply Easy Learning

); Further, assume each employe will have an address, so let us add address specific fields in the same table as follows: create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, street_name VARCHAR(40) default NULL, city_name VARCHAR(40) default NULL, state_name VARCHAR(40) default NULL, zipcode VARCHAR(10) default NULL, PRIMARY KEY (id) );

Define POJO Classes
Let us implement our POJO class Employee which will be used to persist the objects related to EMPLOYEE table. import java.util.*; public class Employee implements java.io.Serializable { private int id; private String firstName; private String lastName; private int salary; private Address address; public Employee() {} public Employee(String fname, String lname, int salary, Address address ) { this.firstName = fname; this.lastName = lname; this.salary = salary; this.address = address; } public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String first_name ) { this.firstName = first_name; } public String getLastName() { return lastName; } public void setLastName( String last_name ) { this.lastName = last_name; } public int getSalary() { return salary;

TUTORIALS POINT Simply Easy Learning

} public void setSalary( int salary ) { this.salary = salary; } public Address getAddress() { return address; } public void setAddress( Address address ) { this.address = address; } } We need to define another POJO class corresponding to ADDRESS entity having address related fields. import java.util.*; public class Address{ private int id; private String street; private String city; private String state; private String zipcode; public Address() {} public Address(String street, String city, String state, String zipcode) { this.street = street; this.city = city; this.state = state; this.zipcode = zipcode; } public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getStreet() { return street; } public void setStreet( String street ) { this.street = street; } public String getCity() { return city; } public void setCity( String city ) { this.city = city; } public String getState() { return state; } public void setState( String state ) { this.state = state; } public String getZipcode() { return zipcode; } public void setZipcode( String zipcode ) {

TUTORIALS POINT Simply Easy Learning

We saved our mapping document in the file Employee.xml. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="name" column="certificate_name" type="string"/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>. contains two <class> elements corresponding to each class. TUTORIALS POINT Simply Easy Learning . The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.hbm.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail.org/dtd/hibernate-mapping-3. this mapping types will convert from Java to SQL data type.  The <meta> element is optional element and can be used to create the class description.hbm.this. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <component name="address" class="Address"> <property name="street" column="street_name" type="string"/> <property name="city" column="city_name" type="string"/> <property name="state" column="state_name" type="string"/> <property name="zipcode" column="zipcode" type="string"/> </component> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> <class name="Certificate" table="CERTIFICATE"> <meta attribute="class-description"> This class contains the certificate records. } } Define Hibernate Mapping File Let us develop our mapping file which instructs Hibernate how to map the defined classes to the database tables.  The <id> element maps the unique ID attribute in class to the primary key of the database table. The <component> element will be used to define the rule for all the fields associated with ADDRESS table.hibernate.xml.0.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www. The type attribute holds the hibernate mapping type. You are already familiar with most of the mapping detail but let us see all the elements of mapping file once again:  The mapping document is an XML document having <hibernate-mapping> as the root element which  The <class> elements are used to define specific mappings from a Java classes to the database tables.zipcode = zipcode. <?xml version="1.

println("Failed to create sessionFactory object.updateEmployee(empID1. address1). this mapping types will convert from Java to SQL data type.Transaction. "Kumar"."111").openSession(). TUTORIALS POINT Simply Easy Learning . The type attribute holds the hibernate mapping type. org. } /* Method to add an address record in the database */ public Address addAddress(String street. /* Update employee's salary records */ ME.addAddress("Saharanpur". import java. "Kumar"."UP"."532").hibernate.addAddress("Kondapur".util."AP". sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database.configure(). Transaction tx = null. /* Add employee records in the database */ Integer empID1 = ME. } ManageEmployee ME = new ManageEmployee(). String city.hibernate. }catch (Throwable ex) { System.buildSessionFactory()." + ex).*.listEmployees().cfg.addEmployee("Dilip". Set the class attribute of the generator element is set to native to let hibernate pick up either identity. Integer addressID = null. public class ManageEmployee { private static SessionFactory factory.hibernate. String zipcode) { Session session = factory. /* Add another employee record in the database */ Integer empID2 = ME.addEmployee("Manoj". The <generator> element within the id element is used to automatically generate the primary key values. public static void main(String[] args) { try{ factory = new Configuration(). org. String state.err. org.  The <property> element is used to map a Java class property to a column in the database table. Create Application Class Finally. address2). /* List down all the employees */ ME. /* Let us have one address object */ Address address1 = ME. 4000. import import import import import org. 5000).hibernate. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. /* Let us have another address object */ Address address2 = ME.  The <component> element sets the existence of different attributes of Address class inside Employee classes."Hyderabad".SessionFactory. 3000.HibernateException. org. throw new ExceptionInInitializerError(ex).Configuration. We will use this application to save few Employee's records alongwith their certificates and then we will apply CRUD operations on those records."Ambehta".listEmployees().Session.hibernate. /* List down all the employees */ ME. we will create our application class with the main() method to run the application.

rollback().close(). System.close().rollback().){ Employee employee = (Employee) iterator.getCity()). System.printStackTrace().getState()). System.createQuery("FROM Employee").out. state. System.out.out. } /* Method to list all the employees detail */ public void listEmployees( ){ Session session = factory. e.hasNext().println("\tStreet: " + add. int salary ){ Session session = factory.printStackTrace(). try{ tx = session.save(employee). Transaction tx = null.out. lname.beginTransaction().openSession(). System. System. addressID = (Integer) session. address).print(" Last Name: " + employee.openSession(). Address add = employee.getAddress(). Transaction tx = null.save(address). iterator. }catch (HibernateException e) { if (tx!=null) tx.getSalary()). Address address){ Session session = factory. e.getLastName()).println(" Salary: " + employee.list().getFirstName()). } return employeeID. int salary.beginTransaction(). zipcode).out. address = new Address(street.beginTransaction().next(). tx. city.out.Address address = null.getStreet()). for (Iterator iterator = employees. }finally { session.openSession(). System.println("Address ").printStackTrace(). try{ TUTORIALS POINT Simply Easy Learning . System. } /* Method to add an employee record in the database */ public Integer addEmployee(String fname. Transaction tx = null. String lname. }finally { session.out. tx.println("\tCity: " + add.commit(). }finally { session.commit(). Employee employee = new Employee(fname.out. } tx.println("\tZipcode: " + add. e. try{ tx = session. List employees = session. }catch (HibernateException e) { if (tx!=null) tx. try{ tx = session.close(). } return address. } } /* Method to update salary for an employee */ public void updateEmployee(Integer EmployeeID.rollback().print("First Name: " + employee. Integer employeeID = null.iterator(). }catch (HibernateException e) { if (tx!=null) tx.getZipcode()). employeeID = (Integer) session.println("\tState: " + add.commit(). salary.

close(). }catch (HibernateException e) { if (tx!=null) tx.java source file as shown above and compile it.... tx.. Create ManageEmployee. EmployeeID)..tx = session. } } } Compilation and Execution Here are the steps to compile and run the above mentioned application.xml configuration file as explained in configuration chapter.commit().cfg. First Name: Manoj Last Name: Address Street: Kondapur City: Hyderabad State: AP Zipcode: 532 First Name: Dilip Last Name: Address Street: Saharanpur City: Ambehta State: UP Zipcode: 111 First Name: Manoj Last Name: Address Street: Kondapur City: Hyderabad State: AP Zipcode: 532 First Name: Dilip Last Name: Address Street: Saharanpur City: Ambehta State: UP Kumar Salary: 4000 Kumar Salary: 3000 Kumar Salary: 5000 Kumar Salary: 3000 TUTORIALS POINT Simply Easy Learning .setSalary( salary ).. }finally { session. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.xml mapping file as shown above.VARIOUS LOG MESSAGES WILL DISPLAY HERE.java source file as shown above and compile it. $java ManageEmployee . You would get following result on the screen.hbm.      Create hibernate.beginTransaction().. Employee employee = (Employee)session. and same time records would be created in EMPLOYEE table.class.. e..rollback()..printStackTrace(). Execute ManageEmployee binary to run the program..update(employee).get(Employee. session.. Create Employee. employee.. Create Employee.

00 sec) mysql> TUTORIALS POINT Simply Easy Learning . street_name. state_name from EMPLOYEE.Zipcode: 111 If you check your EMPLOYEE table. +----+------------+--------+-------------+------------+ | id | first_name | salary | street_name | state_name | +----+------------+--------+-------------+------------+ | 1 | Manoj | 5000 | Kondapur | AP | | 2 | Dilip | 3000 | Saharanpur | UP | +----+------------+--------+-------------+------------+ 2 rows in set (0.salary. first_name. it should have following records: mysql> select id.

jar and lib/ejb3-persistence. salary INT default NULL. If you going to make your application portable to other EJB 3 compliant ORM applications. Environment Setup for Hibernate Annotation First of all you would have to make sure that you are using JDK 5. you will need to install the Hibernate 3.0 to take advantage of the native support for annotations. Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping. All the metadata is clubbed into the POJO java file along with the code this helps the user to understand the table structure and POJO simultaneously during the development.0 otherwise you need to upgrade your JDK to JDK 5.jar. You can use annotations in addition to or as a replacement of XML mapping metadata. Second. lib/hibernate-comonsannotations. last_name VARCHAR(20) default NULL.jar from the Hibernate Annotations distribution to your CLASSPATH Annotated Class Example As I mentioned above while working with Hibernate Annotation all the metadata is clubbed into the POJO java file along with the code this helps the user to understand the table structure and POJO simultaneously during the development.CHAPTER 12 Hibernate Annotations S o far you have seen how Hibernate uses XML mapping file for the transformation of data from POJO to database tables and vice versa.x annotations distribution package. you must use annotations to represent the mapping information but still if you want greater flexibility then you should go with XML-based mappings. first_name VARCHAR(20) default NULL. available from the sourceforge: (Download Hibernate Annotation) and copy hibernate-annotations. Consider we are going to use following EMPLOYEE table to store our objects: create table EMPLOYEE ( id INT NOT NULL auto_increment. Hibernate annotations is the newest way to define mappings without a use of XML file. PRIMARY KEY (id) ). TUTORIALS POINT Simply Easy Learning .

*.salary = salary. } public void setFirstName( String first_name ) { this.id = id. Second we used the @Entity annotation to the Employee class which marks this class as an entity bean. } public void setId( int id ) { this. TUTORIALS POINT Simply Easy Learning . } public void setLastName( String last_name ) { this.persistence package.lastName = last_name.persistence. @Column(name = "last_name") private String lastName. Hence. public Employee() {} public int getId() { return id. } public String getLastName() { return lastName. } public int getSalary() { return salary.Following is the mapping of Employee class with annotations to map objects with the defined EMPLOYEE table: import javax. @Entity @Table(name = "EMPLOYEE") public class Employee { @Id @GeneratedValue @Column(name = "id") private int id. } } Hibernate detects that the @Id annotation is on a field and assumes that it should access properties on an object directly through fields at runtime. so we import this package as the first step. If you placed the @Id annotation on the getId() method. you would enable access to properties through getter and setter methods by default. following the selected strategy. Following section will explain the annotations used in the above class. } public String getFirstName() { return firstName. all other annotations are also placed on either fields or getter methods.firstName = first_name. so it must have a no-argument constructor that is visible with at least protected scope. @Entity Annotation The EJB 3 standard annotations are contained in the javax. @Column(name = "salary") private int salary. @Column(name = "first_name") private String firstName. } public void setSalary( int salary ) { this.

import import import import import import org.Iterator.hibernate. public static void main(String[] args) { try{ factory = new AnnotationConfiguration().hibernate. The @Table annotation provides four attributes. nullable attribute permits the column to be marked NOT NULL when the schema is generated. You can use column annotation with the following most commonly used attributes:     name attribute permits the name of the column to be explicitly specified.AnnotationConfiguration. addAnnotatedClass(Employee. }catch (Throwable ex) { System.util. The primary key can be a single field or a combination of multiple fields depending on your table structure. configure(). For now we are using just table name which is EMPLOYEE.Configuration.hibernate. //addPackage("com. throw new ExceptionInInitializerError(ex).xyz") //add package if used. and its schema. buildSessionFactory(). We will use this application to save few Employee's records and then we will apply CRUD operations on those records. which you annotate on the class with the @Id annotation. import java. @Column Annotation The @Column annotation is used to specify the details of the column to which a field or property will be mapped. TUTORIALS POINT Simply Easy Learning .hibernate. } ManageEmployee ME = new ManageEmployee(). Create Application Class Finally. length attribute permits the size of the column used to map a value particularly for a String value.err.SessionFactory." + ex). org. org.class).util. import java. its catalogue. By default. @Id and @GeneratedValue Annotations Each entity bean will have a primary key.@Table Annotation The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database. Letting Hibernate determine which generator type to use makes your code portable between different databases. import java.hibernate. org. the @Id annotation will automatically determine the most appropriate primary key generation strategy to be used but you can override this by applying the @GeneratedValue annotation which takes two parameters strategy and generator which I'm not going to discuss here.util.hibernate.Date.println("Failed to create sessionFactory object. unique attribute permits the column to be marked as containing only unique values. org.Session.Transaction. so let us use only default the default key generation strategy. we will create our application class with the main() method to run the application.HibernateException. and enforce unique constraints on columns in the table. org. allowing you to override the name of the table.List.cfg. public class ManageEmployee { private static SessionFactory factory.cfg.

10000). List employees = session.beginTransaction(). }catch (HibernateException e) { if (tx!=null) tx. Integer empID3 = ME. Transaction tx = null.deleteEmployee(empID2).setSalary(salary). "Paul".listEmployees(). "Ali"./* Add few employee records in database */ Integer empID1 = ME.next().println(" Salary: " + employee. Employee employee = TUTORIALS POINT Simply Easy Learning . try{ tx = session. for (Iterator iterator = employees.updateEmployee(empID1.out.openSession().print(" Last Name: " + employee. Integer empID2 = ME. try{ tx = session. Transaction tx = null. System.openSession().openSession().rollback().createQuery("FROM Employee").setLastName(lname). }finally { session.listEmployees(). employee.commit(). Transaction tx = null. /* Delete an employee from the database */ ME. Integer employeeID = null. /* List down new list of the employees */ ME. /* Update employee's records */ ME.addEmployee("John". int salary){ Session session = factory.printStackTrace().getLastName()). e.list().out. String lname.beginTransaction().){ Employee employee = (Employee) iterator.commit(). /* List down all the employees */ ME. Employee employee = new Employee(). System. tx.iterator().out.addEmployee("Daisy". System. "Das". } } /* Method to UPDATE salary for an employee */ public void updateEmployee(Integer EmployeeID. employee. } /* Method to CREATE an employee in the database */ public Integer addEmployee(String fname. }finally { session.getSalary()).close(). 5000). } /* Method to READ all the employees */ public void listEmployees( ){ Session session = factory.beginTransaction().close(). iterator. }catch (HibernateException e) { if (tx!=null) tx.hasNext().save(employee). employeeID = (Integer) session.print("First Name: " + employee. e.addEmployee("Zara". } return employeeID. 5000).rollback(). } tx.setFirstName(fname). int salary ){ Session session = factory. employee. 1000).printStackTrace().getFirstName()). try{ tx = session.

This time we are not going <?xml version="1.printStackTrace().get(Employee.connection.connection.rollback().dialect"> org.connection.jdbc.hibernate.0.xml configuration file to define database related parameters. }finally { session.delete(employee). tx.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration SYSTEM "http://www. tx. employee. session. session.get(Employee.MySQLDialect </property> <property name="hibernate.password"> cohondob </property> </session-factory> TUTORIALS POINT Simply Easy Learning . e.beginTransaction().close(). }catch (HibernateException e) { if (tx!=null) tx.url"> jdbc:mysql://localhost/test </property> <property name="hibernate. EmployeeID).Driver </property> <!-.printStackTrace().class. try{ tx = session.org/dtd/hibernate-configuration-3.close().username"> root </property> <property name="hibernate.driver_class"> com.cfg.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.openSession().(Employee)session. }finally { session. Employee employee = (Employee)session.commit().rollback().hibernate.mysql. } } /* Method to DELETE an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory. e.setSalary( salary ).Assume students is the database name --> <property name="hibernate.dialect.connection. }catch (HibernateException e) { if (tx!=null) tx.update(employee).class. } } } Database Configuration Now let us create hibernate. EmployeeID). Transaction tx = null.commit().

+----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 29 | Zara | Ali | 5000 | | 31 | John | Paul | 10000 | +----+------------+-----------+--------+ 2 rows in set (0. First First First First First Name: Name: Name: Name: Name: Zara Daisy John Zara John Last Name: Ali Salary: 1000 Last Name: Das Salary: 5000 Last Name: Paul Salary: 10000 Last Name: Ali Salary: 5000 Last Name: Paul Salary: 10000 If you check your EMPLOYEE table.java source file as shown above and compile it.VARIOUS LOG MESSAGES WILL DISPLAY HERE.00 sec mysql> TUTORIALS POINT Simply Easy Learning .... You would get following result.</hibernate-configuration> Compilation and Execution Here are the steps to compile and run the above mentioned application. and records would be created in EMPLOYEE table.xml mapping file from the path.     Delete Employee...... Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution. $java ManageEmployee .. it should have following records: mysql> select * from EMPLOYEE. Create Employee. Create ManageEmployee...hbm. Execute ManageEmployee binary to run the program.java source file as shown above and compile it...

Query query = session. specially when you have long queries.createQuery(hql).Employee". Query query = session. Although you can use SQL statements directly with Hibernate using Native SQL but I would recommend to use HQL whenever possible to avoid database portability hassles. For instance. AS Clause The AS clause can be used to assign aliases to the classes in your HQL queries.createQuery(hql). as follows: TUTORIALS POINT Simply Easy Learning . Following is the simple syntax of using FROM clause: String hql = "FROM Employee". FROM and WHERE etc. If you need to fully qualify a class name in HQL. List results = query. The AS keyword is optional and you can also specify the alias directly after the class name.list().list().criteria. and to take advantage of Hibernate's SQL generation and caching strategies. are not case sensitive but properties like table and column names are case sensitive in HQL. List results = query. our previous simple example would be the following: String hql = "FROM Employee AS E". Keywords like SELECT . but instead of operating on tables and columns.list(). just specify the package and class name as follows: String hql = "FROM com.hibernatebook.createQuery(hql). Query query = session.CHAPTER 13 Hibernate Query Language H ibernate Query Language (HQL) is an object-oriented query language. HQL queries are translated by Hibernate into conventional SQL queries which in turns perform action on database. List results = query. HQL works with persistent objects and their properties. FROM Clause You will use FROM clause if you want to load a complete persistent objects into memory. similar to SQL.

List results = query.list(). TUTORIALS POINT Simply Easy Learning .createQuery(hql).salary DESC". Query query = session. If you wanted to sort by more than one property. Following is the simple syntax of using GROUP BY clause: String hql = "SELECT SUM(E.createQuery(hql).firstName FROM Employee E". GROUP BY Clause This clause lets Hibernate pull information from the database and group it based on a value of an attribute and. separated by commas as follows: String hql = "FROM Employee E WHERE E. Following is the simple syntax of using ORDER BY clause: String hql = "FROM Employee E WHERE E.salary DESC ". List results = query. typically.String hql = "FROM Employee E".firtName FROM Employee E " + "GROUP BY E. you would just add the additional properties to the end of the order by clause.id > 10 " + "ORDER BY E. List results = query. ORDER BY Clause To sort your HQL query's results.firstName". E. If you want to obtain few properties of objects instead of the complete object.id > 10 ORDER BY E.list(). You can order the results by any property on the objects in the result set either ascending (ASC) or descending (DESC).firstName DESC. Following is the simple syntax of using WHERE clause: String hql = "FROM Employee E WHERE E. use the result to include an aggregate value. Query query = session.createQuery(hql). Query query = session.firstName is a property of Employee object rather than a field of the EMPLOYEE table.list().createQuery(hql).list(). E. Following is the simple syntax of using SELECT clause to get just first_name field of the Employee object: String hql = "SELECT E.list().id = 10". List results = query. SELECT Clause The SELECT clause provides more control over the result set than the from clause.createQuery(hql). you use the WHERE clause. Query query = session.salary). use the SELECT clause. It is notable here that Employee.list(). Query query = session. List results = query. you will need to use the ORDER BY clause. WHERE Clause If you want to narrow the specific objects that are returned from storage.createQuery(hql). List results = query. Query query = session.

+ DELETE Clause The DELETE clause can be used to delete one or more objects. query.out. The UPDATE clause can be used to update one or more properties of an one or more objects.id = :employee_id". List results = query. salary)" + "SELECT firstName.createQuery(hql). Query query = session. salary FROM old_employee".createQuery(hql). Following is the simple syntax of using UPDATE clause: String hql = "UPDATE Employee set salary = :salary " "WHERE id = :employee_id".out. 1000). 10). System. query. They work the same way in HQL as in SQL and following is the list of the available functions: TUTORIALS POINT Simply Easy Learning . This makes writing HQL queries that accept input from the user easy and you do not have to defend against SQL injection attacks. Following is the simple syntax of using INSERT INTO clause: String hql = "INSERT INTO Employee(firstName.println("Rows affected: " + result). INSERT Clause HQL supports INSERT INTO clause only where records can be inserted from one object to another object. The Query interface now contains a method called executeUpdate() for executing HQL UPDATE or DELETE statements.println("Rows affected: " + result). int result = query.10). Following is the simple syntax of using named parameters: String hql = "FROM Employee E WHERE E.list().createQuery(hql).createQuery(hql).executeUpdate().setParameter("salary".executeUpdate(). lastName. Query query = session.out. lastName. Query query = session.println("Rows affected: " + result).Using Named Paramters Hibernate supports named parameters in its HQL queries. int result = query.setParameter("employee_id". 10). and deletes work differently in Hibernate 3 than they did in Hibernate 2. similar to SQL. int result = query. System.setParameter("employee_id". UPDATE Clause Bulk updates are new to HQL with Hibernate 3. query.setParameter("employee_id". Query query = session. query. Aggregate Methods HQL supports a range of aggregate methods. Following is the simple syntax of using DELETE clause: String hql = "DELETE FROM Employee " + "WHERE id = :employee_id".executeUpdate(). System.

S. Pagination using Query There are two methods of the Query interface for pagination.N. Following is the example which you can extend to fetch 10 rows at a time: String hql = "FROM Employee". The following query will return only unique count: String hql = "SELECT count(distinct E.list(). Using above two methods together. we can construct a paging component in our web or Swing application. starting with row 0. TUTORIALS POINT Simply Easy Learning . Query setMaxResults(int maxResult) This method tells Hibernate to retrieve a fixed number maxResults of objects. Query query = session. query. List results = query.createQuery(hql). List results = query.setFirstResult(1).setMaxResults(10).firstName) FROM Employee E". query. Method & Description 1 2 Query setFirstResult(int startPosition) This method takes an integer that represents the first row in your result set.N.list(). Query query = session. Functions 1 2 3 4 5 avg(property name) count(property name or *) max(property name) min(property name) sum(property name) Description The average of a property's value The number of times a property occurs in the results The maximum value of the property values The minimum value of the property values The sum total of the property values The distinct keyword only counts the unique values in the row set.createQuery(hql). S.

createCriteria(Employee.list(). Restrictions with Criteria You can use add() method available for Criteria object to add restriction for a criteria query.eq("salary".lt("salary". 2000)). 2000)). "zara%")). One of the methods is Criteria API which allows you to build up a criteria query object programmatically where you can apply filtration rules and logical conditions.gt("salary".createCriteria(Employee. Following is the simplest example of a criteria query is one which will simply return every object that corresponds to the Employee class. // To get records having salary less than 2000 cr. Criteria cr = session.createCriteria(Employee. // To get records having salary more than 2000 cr. List results = cr.like("firstName".add(Restrictions. TUTORIALS POINT Simply Easy Learning .CHAPTER 14 Hibernate Criteria Queries H ibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables. The Hibernate Session interface provides createCriteria() method which can be used to create a Criteria object that returns instances of the persistence object's class when your application executes a criteria query.class). // Case sensitive form of the above restriction. Following is the example to add a restriction to return the records with salary is equal to 2000: Criteria cr = session.class). Following are the few more examples covering different scenarios and can be used as per requirement: Criteria cr = session.add(Restrictions.class). // To get records having fistName starting with zara cr.list(). 2000)). cr. List results = cr.add(Restrictions.add(Restrictions.

List results = cr. cr.add( andExp ). cr.add(Restrictions.or(salary.createCriteria(Employee. Using above two methods together.add(Restrictions. Pagination using Criteria There are two methods of the Criteria interface for pagination. // To check if the given property is empty cr."zara%"). Though all the above conditions can be used directly with HQL as explained in previous tutorial. 2000). Method & Description 1 2 public Criteria setFirstResult(int firstResult) This method takes an integer that represents the first row in your result set. name).cr. TUTORIALS POINT Simply Easy Learning .gt("salary". Following is the example which you can extend to fetch 10 rows at a time: Criteria cr = session.ilike("firstName". 1000. Criterion salary = Restrictions.add(Restrictions. // To get records having salary in between 1000 and 2000 cr.ilike("firstNname".list().and(salary.add(Restrictions. You can create AND or OR conditions using LogicalExpression restrictions as follows: Criteria cr = session.isNull("salary")). we can construct a paging component in our web or Swing application.add( orExp ).setFirstResult(1). // To check if the given property is not null cr.class). S.isNotNull("salary")).list().N.between("salary". // To get records matching with OR condistions LogicalExpression orExp = Restrictions.isNotEmpty("salary")). cr. 2000)).add(Restrictions. starting with row 0.setMaxResults(10).class).add(Restrictions. Criterion name = Restrictions. // To get records matching with AND condistions LogicalExpression andExp = Restrictions.isEmpty("salary")). "zara%")). // To check if the given property is null cr. public Criteria setMaxResults(int maxResults) This method tells Hibernate to retrieve a fixed number maxResults of objects. // To check if the given property is not empty cr. List results = cr.createCriteria(Employee. cr. name).

addOrder(Order. // To get average of a property.rowCount()).setProjection(Projections.min("salary")). cr.desc("salary")). Projections & Aggregations The Criteria API provides the org. This example demonstrates how you would use the Order class to sort the result set: Criteria cr = session.criterion. // To get minimum of a property.sum("salary")). 2000)). cr.setProjection(Projections.Sorting the Results The Criteria API provides the org.setProjection(Projections. cr.addOrder(Order.list().setProjection(Projections.hibernate.max("salary")).class).Order class to sort your result set in either ascending or descending order. // To sort records in ascending order crit. TUTORIALS POINT Simply Easy Learning .createCriteria(Employee. maximum or minimum of the property values. // To get maximum of a property. The Projections class is similar to the Restrictions class in that it provides several static factory methods for obtaining Projection instances. according to one of your object's properties. private String firstName. // To get total row count. Criteria Queries Example Consider the following POJO class: public class Employee { private int id.criterion.class).avg("salary")).setProjection(Projections.countDistinct("firstName")).setProjection(Projections. cr. // To sort records in descening order crit. // To get distinct count of a property.Projections class which can be used to get average. cr. List results = cr. // To get records having salary more than 2000 cr. cr.asc("salary")).hibernate.createCriteria(Employee. // To get sum of a property. Following are the few examples covering different scenarios and can be used as per requirement: Criteria cr = session.gt("salary".add(Restrictions.

salary = salary.org/dtd/hibernate-mapping-3.lastName = lname. } public void setSalary( int salary ) { this.0. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> TUTORIALS POINT Simply Easy Learning .hibernate.lastName = last_name.salary = salary. } } Let us create the following EMPLOYEE table to store Employee objects: create table EMPLOYEE ( id INT NOT NULL auto_increment. salary INT default NULL. } public int getId() { return id. } public String getLastName() { return lastName. } public void setId( int id ) { this. private int salary. PRIMARY KEY (id) ). first_name VARCHAR(20) default NULL.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. Following will be mapping file. public Employee() {} public Employee(String fname. } public int getSalary() { return salary.firstName = fname. } public void setFirstName( String first_name ) { this. last_name VARCHAR(20) default NULL. } public String getFirstName() { return firstName. } public void setLastName( String last_name ) { this.firstName = first_name. String lname. <?xml version="1. this.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.id = id.private String lastName. this. int salary) { this.

tx. "Yasee".List.Restrictions.beginTransaction().Session. }catch (HibernateException e) { if (tx!=null) tx.Configuration. 5000). org. we will create our application class with the main() method to run the application where we will use Criteria queries: import java. public static void main(String[] args) { try{ factory = new Configuration().totalSalary(). int salary){ Session session = factory.rollback().criterion. Employee employee = new Employee(fname. Integer empID3 = ME.hibernate. } TUTORIALS POINT Simply Easy Learning . public class ManageEmployee { private static SessionFactory factory. import import import import import import import import org. try{ tx = session.criterion. String lname. Integer empID4 = ME. Integer employeeID = null. org.addEmployee("Daisy".countEmployee().hibernate.util. org. /* Print Total employee's count */ ME.addEmployee("Zara". Transaction tx = null. } ManageEmployee ME = new ManageEmployee().listEmployees().save(employee). } return employeeID.err.openSession(). Integer empID2 = ME.hibernate. salary).SessionFactory.hibernate.Criteria. } /* Method to CREATE an employee in the database */ public Integer addEmployee(String fname. /* List down all the employees */ ME.println("Failed to create sessionFactory object. "Das". org." + ex). }catch (Throwable ex) { System.util.hibernate. "Ali".Transaction. org. lname.Projections.<property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> </hibernate-mapping> Finally. throw new ExceptionInInitializerError(ex). "Paul".commit(). import java. import java. employeeID = (Integer) session.HibernateException.hibernate.addEmployee("Mohd".hibernate.printStackTrace(). }finally { session.buildSessionFactory().util. 3000). org. /* Add few employee records in database */ Integer empID1 = ME.addEmployee("John". 2000).Date.hibernate. e.close().Iterator.configure().cfg. 5000). /* Print Toatl salary */ ME. org.

class). Transaction tx = null. iterator.out. e.createCriteria(Employee.print(" Last Name: " + employee. }finally { session. } } /* Method to print sum of salaries */ public void totalSalary(){ Session session = factory.rowCount()).close(). // To get total salary.getLastName()).setProjection(Projections.list(). }catch (HibernateException e) { if (tx!=null) tx.setProjection(Projections. System. }catch (HibernateException e) { if (tx!=null) tx. try{ tx = session.out. Transaction tx = null. // Add restriction.printStackTrace().printStackTrace(). cr.list().get(0) ). Transaction tx = null.rollback().print("First Name: " + employee. System.beginTransaction(). Criteria cr = session.get(0) ).println("Total Salary: " + totalSalary. } tx.out. System.close(). System.){ Employee employee = (Employee) iterator. List totalSalary = cr.getFirstName()). cr.println("Total Coint: " + rowCount.commit(). e.sum("salary")).openSession(). tx. e.hasNext().commit().createCriteria(Employee.add(Restrictions. System. } } /* Method to print total number of records */ public void countEmployee(){ Session session = factory. try{ tx = session.out.rollback().next().getSalary()). List rowCount = cr. List employees = cr.printStackTrace(). }finally { session.beginTransaction(). tx. cr. }finally { session.class).createCriteria(Employee.rollback(). try{ tx = session.openSession().class). // To get total row count.beginTransaction(). 2000)). Criteria cr = session.out.commit(). for (Iterator iterator = employees.println(" Salary: " + employee.list().close().iterator(). }catch (HibernateException e) { if (tx!=null) tx. } } TUTORIALS POINT Simply Easy Learning .openSession().gt("salary". Criteria cr = session./* Method to READ all the employees having salary more than 2000 */ public void listEmployees( ){ Session session = factory.

.VARIOUS LOG MESSAGES WILL DISPLAY HERE.      Create hibernate. Execute ManageEmployee binary to run the program. Create ManageEmployee.00 sec) mysql> TUTORIALS POINT Simply Easy Learning ... and records would be created in EMPLOYEE table.java source file as shown above and compile it. Create Employee..hbm.cfg. Create Employee.java source file as shown above and compile it..xml configuration file as explained in configuration chapter. $java ManageEmployee ... +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 14 | Zara | Ali | 2000 | | 15 | Daisy | Das | 5000 | | 16 | John | Paul | 5000 | | 17 | Mohd | Yasee | 3000 | +----+------------+-----------+--------+ 4 rows in set (0.xml mapping file as shown above.. You would get following result.} Compilation and Execution Here are the steps to compile and run the above mentioned application. it should have following records: mysql> select * from EMPLOYEE. First First First Total Total Name: Daisy Last Name: Das Salary: 5000 Name: John Last Name: Paul Salary: 5000 Name: Mohd Last Name: Yasee Salary: 3000 Coint: 4 Salary: 15000 If you check your EMPLOYEE table.. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.....

List results = query. delete.ALIAS_TO_ENTITY_MAP). Entity queries The above queries were all about returning scalar values.class). Scalar queries The most basic SQL query is to get a list of scalars (values) from one or more tables. query. The following is the syntax to get entity objects as a whole from a native sql query via addEntity(). List results = query.x allows you to specify handwritten SQL. you can associate the SQL result with either an existing Hibernate entity.createSQLQuery(sql).CHAPTER 15 Hibernate Native SQL Y ou can use native SQL to express database queries if you want to utilize database-specific features such as query hints or the CONNECT keyword in Oracle. SQLQuery query = session.createSQLQuery(sql). a join. SQLQuery query = session. update. and load operations. String sql = "SELECT * FROM EMPLOYEE".list(). basically returning the "raw" values from the resultset. addJoin().setResultTransformer(Criteria. salary FROM EMPLOYEE".list(). for all create. Your application will create a native SQL query from the session with the createSQLQuery() method on the Session interface: public SQLQuery createSQLQuery(String sqlString) throws HibernateException After you pass a string containing the SQL query to the createSQLQuery() method. query. Hibernate 3. and addScalar() methods respectively. TUTORIALS POINT Simply Easy Learning .addEntity(Employee. or a scalar result using addEntity(). Following is the syntax for using native SQL for scalar values: String sql = "SELECT first_name. including stored procedures.

this. private int salary. Native SQL Example Consider the following POJO class: public class Employee { private int id.firstName = first_name.lastName = last_name. query.salary = salary. } } Let us create the following EMPLOYEE table to store Employee objects: TUTORIALS POINT Simply Easy Learning . } public int getId() { return id.addEntity(Employee. SQLQuery query = session. } public void setLastName( String last_name ) { this. } public void setFirstName( String first_name ) { this.firstName = fname. String lname. } public void setSalary( int salary ) { this. public Employee() {} public Employee(String fname. List results = query. private String lastName. } public void setId( int id ) { this. private String firstName. this. String sql = "SELECT * FROM EMPLOYEE WHERE id = :employee_id". } public String getLastName() { return lastName. } public int getSalary() { return salary.lastName = lname.salary = salary. query. int salary) { this.setParameter("employee_id".class). } public String getFirstName() { return firstName. 10).Named SQL queries The following is the syntax to get entity objects from a native sql query via addEntity() and using named SQL query.id = id.createSQLQuery(sql).list().

hibernate. "Das".util.*. }catch (Throwable ex) { System.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail." + ex).hibernate. we will create our application class with the main() method to run the application where we will use Native SQL queries: import java. 5000). 5000).hibernate. 3000).err. Integer empID2 = ME. /* Add few employee records in database */ Integer empID1 = ME.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate. /* List down complete employees information using Entity Query */ TUTORIALS POINT Simply Easy Learning .addEmployee("John".SessionFactory. public class ManageEmployee { private static SessionFactory factory.listEmployeesScalar(). org.hibernate.Session. org.println("Failed to create sessionFactory object. first_name VARCHAR(20) default NULL. org.hibernate.org/dtd/hibernate-mapping-3. Integer empID4 = ME. Following will be mapping file.addEmployee("Zara". </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> </hibernate-mapping> Finally.buildSessionFactory(). org.addEmployee("Mohd".Transaction.hibernate. 2000). PRIMARY KEY (id) ).0. throw new ExceptionInInitializerError(ex).hibernate. /* List down employees and their salary using Scalar Query */ ME. "Yasee". public static void main(String[] args) { try{ factory = new Configuration(). last_name VARCHAR(20) default NULL. "Paul".HibernateException.Criteria. Integer empID3 = ME.create table EMPLOYEE ( id INT NOT NULL auto_increment. } ManageEmployee ME = new ManageEmployee().Hibernate. org. salary INT default NULL. org.Configuration. <?xml version="1. import import import import import import import import org. org.hibernate.configure(). "Ali".cfg.SQLQuery.addEmployee("Daisy".

out. } /* Method to READ all the employees using Scalar Query */ public void listEmployeesScalar( ){ Session session = factory.hasNext(). List data = query. } tx.close(). System.addEntity(Employee.print("First Name: " + employee.beginTransaction().get("first_name")). query.commit(). Transaction tx = null.printStackTrace(). Employee employee = new Employee(fname. System. Transaction tx = null. }catch (HibernateException e) { if (tx!=null) tx.println(". List employees = query.printStackTrace(). salary FROM EMPLOYEE". e.listEmployeesEntity(). }catch (HibernateException e) { if (tx!=null) tx. Integer employeeID = null. }catch (HibernateException e) { if (tx!=null) tx. employeeID = (Integer) session.commit(). TUTORIALS POINT Simply Easy Learning .ME. } return employeeID. for(Object object : data) { Map row = (Map)object. Transaction tx = null.openSession().class).out.print(" Last Name: " + employee.save(employee). }finally { session.out.println(" Salary: " + employee. String sql = "SELECT first_name. SQLQuery query = session. String sql = "SELECT * FROM EMPLOYEE".get("salary")).ALIAS_TO_ENTITY_MAP).commit(). System. try{ tx = session.createSQLQuery(sql).openSession(). SQLQuery query = session.setResultTransformer(Criteria. Salary: " + row.getFirstName()). System. salary).out.rollback().list(). }finally { session.getSalary()).){ Employee employee = (Employee) iterator.print("First Name: " + row. tx. query.createSQLQuery(sql).beginTransaction(). System. int salary){ Session session = factory.iterator(). } tx.beginTransaction().rollback(). iterator.list(). } } /* Method to READ all the employees using Entity Query */ public void listEmployeesEntity( ){ Session session = factory.next().close().getLastName()). lname. String lname. try{ tx = session. } /* Method to CREATE an employee in the database */ public Integer addEmployee(String fname. e.openSession().out.rollback(). for (Iterator iterator = employees. try{ tx = session.

+----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 26 | Zara | Ali | 2000 | | 27 | Daisy | Das | 5000 | | 28 | John | Paul | 5000 | | 29 | Mohd | Yasee | 3000 | +----+------------+-----------+--------+ 4 rows in set (0. Create ManageEmployee. Execute ManageEmployee binary to run the program.xml mapping file as shown above. and records would be created in EMPLOYEE table. Create Employee. } } } Compilation and Execution Here are the steps to compile and run the above mentioned application.. Salary: 5000 Mohd.hbm.. You would get following result.printStackTrace().. First First First First First First First First Name: Name: Name: Name: Name: Name: Name: Name: Zara. }finally { session.java source file as shown above and compile it.. Salary: 2000 Daisy. Create Employee.e. Salary: 5000 John. $java ManageEmployee . it should have following records: mysql> select * from EMPLOYEE. Salary: 3000 Zara Last Name: Ali Salary: 2000 Daisy Last Name: Das Salary: 5000 John Last Name: Paul Salary: 5000 Mohd Last Name: Yasee Salary: 3000 If you check your EMPLOYEE table.VARIOUS LOG MESSAGES WILL DISPLAY HERE...java source file as shown above and compile it..cfg..... Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.00 sec) mysql> TUTORIALS POINT Simply Easy Learning .      Create hibernate.xml configuration file as explained in configuration chapter..close()..

TUTORIALS POINT Simply Easy Learning . Caching is important to Hibernate as well which utilizes a multilevel caching schemes as explained below: First-level cache The first-level cache is the Session cache and is a mandatory cache through which all requests must pass.CHAPTER 16 Hibernate Caching C aching is all about application performance optimization and it sits between your application and the database to avoid the number of database hits as many as possible to give a better performance for performance critical applications. The Session object keeps an object under its own power before committing it to the database.

First. transactions. The second-level cache can be configured on a per-class and percollection basis and mainly responsible for caching objects across sessions.hibernate. which cache concurrency strategy to use. so it's important to be able to disable the second-level cache The Hibernate second-level cache is set up in two steps. Any third-party cache can be used with Hibernate.hibernate. Query-level cache Hibernate also implements a cache for query resultsets that integrates closely with the second-level cache. Not all classes benefit from caching.0. all the objects being cached are lost and either persisted or updated in the database. which must be implemented to provide Hibernate with a handle to the cache implementation. Use it for reference data only. After that.org/dtd/hibernate-mapping-3. If you are going to enable a second-level cache. TUTORIALS POINT Simply Easy Learning . transactions. Second-level cache Second level cache is an optional cache and first-level cache will always be consulted before any attempt is made to locate an object in the second-level cache. This is only useful for queries that are run frequently with the same parameters. If you close the session. Hibernate tries to delay doing the update as long as possible to reduce the number of update SQL statements issued. Concurrency strategies A concurrency strategy is a mediator which responsible for storing items of data in the cache and retrieving them from the cache.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> Use this strategy if data hardly ever changes and a small likelihood of stale data is not of critical concern. Let's go straight to the optional second-level cache.If you issue multiple updates to an object. If we are going to use second-level caching for our Employee class.in the rare case of an update. for each persistent class and collection.in the rare case of an update.cache. The Second Level Cache Hibernate uses first-level cache by default and you have nothing to do to use first-level cache. you configure cache expiration and physical cache attributes using the cache provider. you have to decide which concurrency strategy to use. you will have to decide. <?xml version="1.CacheProvider interface is provided.  Transactional: Use this strategy for read-mostly data where it is critical to prevent stale data in concurrent  Read-write: Again use this strategy for read-mostly data where it is critical to prevent stale data in concurrent  Nonstrict-read-write: This strategy makes no guarantee of consistency between the cache and the database. let us add the mapping element required to tell Hibernate to cache Employee instances using read-write strategy.  Read-only: A concurrency strategy suitable for data which never changes.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www. An org. This is an optional feature and requires two additional physical cache regions that hold the cached query results and the timestamps when a table was last updated.

N. A cluster cache based on JGroups.hibernate.xml configuration file.<meta attribute="class-description"> This class contains the employee detail. with a rich set of expiration policies and query cache support. Hibernate forces you to choose a single cache provider for the whole application.0. and optimistic and pessimistic locking. The Hibernate query cache is supported 4 JBoss Cache Every cache provider is not compatible with every concurrency strategy. We choose EHCache as our second-level cache provider: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration SYSTEM "http://www.cfg. Strategy/Provider Read-only EHCache OSCache SwarmCache JBoss Cache X X X X Nonstrictread-write X X X X Read-write X X Transaction al You will specify a cache provider in hibernate. Cache Name 1 2 3 EHCache OSCache warmCache Description It can cache in memory or on disk and clustered caching and it supports the optional Hibernate query result cache. S. Supports caching to memory and disk in a single JVM. </meta> <cache usage="read-write"/> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> </hibernate-mapping> The usage="read-write" attribute tells Hibernate to use a read-write concurrency strategy for the defined cache. synchronous or asynchronous communication. It supports replication or invalidation. The following compatibility matrix will help you choose an appropriate combination. Cache provider Your next step after considering the concurrency strategies you will use for your cache candidate classes is to pick a cache provider.dtd"> TUTORIALS POINT Simply Easy Learning .org/dtd/hibernate-configuration-3. It uses clustered invalidation but doesn't support the Hibernate query cache A fully transactional replicated clustered cache also based on the JGroups multicast library.

username"> root </property> <property name="hibernate. TUTORIALS POINT Simply Easy Learning .cache. Sometime.mysql.provider_class"> org.cache.Driver </property> <!-.connection.dialect.List of XML mapping files --> <mapping resource="Employee.ehcache.jdbc.hibernate. So it is recommended to benchmark your application first without enabling caching and later on enable your well suited caching and check the performance.connection.MySQLDialect </property> <property name="hibernate. you need to specify the properties of the cache regions. second-level caching may downgrade the performance of the application.Assume students is the database name --> <property name="hibernate.xml.EhCacheProvider </property> <!-. now we have second-level caching enabled for the Employee class and Hibernate now hits the secondlevel cache whenever you navigate to a Employee or when you load a Employee by identifier.connection. You should analyze your all the classes and choose appropriate caching strategy for each of the classes.<hibernate-configuration> <session-factory> <property name="hibernate.password"> root123 </property> <property name="hibernate.hibernate. A cache configuration in ehcache.driver_class"> com.tmpdir"/> <defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" /> <cache name="Employee" maxElementsInMemory="500" eternal="true" timeToIdleSeconds="0" timeToLiveSeconds="0" overflowToDisk="false" /> That's it.xml"/> </session-factory> </hibernate-configuration> Now.connection.hbm.url"> jdbc:mysql://localhost/test </property> <property name="hibernate.io.xml for the Employee class may look like this: <diskStore path="java.dialect"> org. which should be in the CLASSPATH of the application. If caching is not improving system performance then there is no point in enabling any type of caching. EHCache has its own configuration file.

For example: Session session = SessionFactory.cache.openSession().setCacheable(true). you must first activate it using the hibernate. query.The Query-level Cache To use the query cache. you use the setCacheable(Boolean) method of the Query class.closeSession().list().setCacheable(true).createQuery("FROM EMPLOYEE"). A cache region is part of the cache that's given a name. query. SessionFactory.list(). Session session = SessionFactory. Query query = session. Next. SessionFactory. query. List users = query. This code uses the method to tell Hibernate to store and look for the query in the employee area of the cache. you make Hibernate create the necessary caches in memory to hold the query and identifier sets. Query query = session.createQuery("FROM EMPLOYEE").setCacheRegion("employee"). to use the query cache.openSession(). By setting this property to true. TUTORIALS POINT Simply Easy Learning . List users = query.closeSession().use_query_cache="true"property in the configuration file. Hibernate also supports very fine-grained cache support through the concept of a cache region.

for ( int i=0. session.flush().. To use the batch processing feature. Transaction tx = session. Transaction tx = session..CHAPTER 17 Hibernate Batch Processing C onsider a situation when you need to upload a large number of records into your database using Hibernate. session. session.beginTransaction().openSession(). for ( int i=0. i++ ) { Employee employee = new Employee(.openSession(). i<100000. session. first set hibernate.close().).commit(). Transaction tx = session. } tx.beginTransaction().000th row. You can resolve this problem if you are using batch processing with Hibernate. This will tell the hibernate container that every X rows to be inserted as batch. TUTORIALS POINT Simply Easy Learning .clear().. session. but if you are willing to make UPDATE operation then you can achieve using the following code: Session session = sessionFactory. } } tx.openSession().jdbc.batch_size as batch size to a number either at 20 or 50 depending on object size. i++ ) { Employee employee = new Employee(.beginTransaction(). Because by default.save(employee)..save(employee)..close().. To implement this in your code we would need to do little modification as follows: Session session = SessionFactory. if( i % 50 == 0 ) { // Same as the JDBC batch size //flush a batch of inserts and release memory: session. Above code will work fine for the INSERT operation..commit().. i<100000. Following is the code snippet to achieve this using Hibernate: Session session = SessionFactory.). Hibernate will cache all the persisted objects in the session-level cache and ultimately your application would fall over with an OutOfMemoryException somewhere around the 50.

employee. session. } } tx.update(employee).dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.scroll().List of XML mapping files --> <mapping resource="Employee.0. Batch Processing Example Let us modify configuration file as to add hibernate.Driver </property> <!-.jdbc.connection.org/dtd/hibernate-configuration-3.connection.connection.jdbc.Assume students is the database name --> <property name="hibernate.createQuery("FROM EMPLOYEE") .driver_class"> com.hibernate.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration SYSTEM "http://www.batch_size property: <?xml version="1.mysql.xml"/> </session-factory> </hibernate-configuration> Consider the following POJO Employee class: TUTORIALS POINT Simply Easy Learning .hbm.ScrollableResults employeeCursor = session.dialect. session. if ( ++count % 50 == 0 ) { session.dialect"> org.updateEmployee().password"> root123 </property> <property name="hibernate.hibernate. seession.url"> jdbc:mysql://localhost/test </property> <property name="hibernate.connection.next() ) { Employee employee = (Employee) employeeCursor.clear().flush().get(0).commit().jdbc.MySQLDialect </property> <property name="hibernate.username"> root </property> <property name="hibernate. while ( employeeCursor. int count = 0.close().batch_size"> 50 </property> <!-.

Following will be mapping file to map Employee objects with EMPLOYEE table.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.0. } public void setSalary( int salary ) { this.salary = salary. this.firstName = first_name.hibernate. first_name VARCHAR(20) default NULL. int salary) { this.firstName = fname.salary = salary. this.public class Employee { private int id. } public String getFirstName() { return firstName. } } Let us create the following EMPLOYEE table to store Employee objects: create table EMPLOYEE ( id INT NOT NULL auto_increment. } public void setId( int id ) { this. } public void setFirstName( String first_name ) { this.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. </meta> TUTORIALS POINT Simply Easy Learning . PRIMARY KEY (id) ). salary INT default NULL. private int salary.lastName = lname.id = id. } public void setLastName( String last_name ) { this.org/dtd/hibernate-mapping-3.lastName = last_name. last_name VARCHAR(20) default NULL. public Employee() {} public Employee(String fname. } public String getLastName() { return lastName. String lname. } public int getSalary() { return salary. private String lastName. <?xml version="1. } public int getId() { return id. private String firstName.

e.err. org. /* Add employee records in batches */ ME. i++ ) { String fname = "First Name " + i.close().rollback(). salary).Transaction. for ( int i=0. public class ManageEmployee { private static SessionFactory factory. String lname = "Last Name " + i.SessionFactory. } return . Employee employee = new Employee(fname. org.printStackTrace(). lname. } /* Method to create employee records in batches */ public void addEmployees( ){ Session session = factory.Configuration.commit().openSession().clear(). import import import import import org. public static void main(String[] args) { try{ factory = new Configuration().flush().hibernate. Integer employeeID = null.beginTransaction().hibernate. if( i % 50 == 0 ) { session.addEmployees( ).util. session.configure(). try{ tx = session. i<100000.hibernate. }catch (Throwable ex) { System.println("Failed to create sessionFactory object.cfg.buildSessionFactory(). import java. Transaction tx = null.save(employee). } ManageEmployee ME = new ManageEmployee(). throw new ExceptionInInitializerError(ex)." + ex). }finally { session.HibernateException. org. org.*.hibernate. we will create our application class with the main() method to run the application where we will use flush() and clear() methods available with Session object so that Hibernate keep writing these records into the database instead of caching them in the memory.Session. } } TUTORIALS POINT Simply Easy Learning . }catch (HibernateException e) { if (tx!=null) tx. session. } } tx.<id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> </hibernate-mapping> Finally. Integer salary = i.hibernate.

 Create Employee.hbm.cfg.  Create hibernate.xml mapping file as shown above.  Create ManageEmployee.xml configuration file as explained above.java source file as shown above and compile it.  Create Employee.  Execute ManageEmployee binary to run the program which will create 100000 records in EMPLOYEE table. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.Compilation and Execution Here are the steps to compile and run the above mentioned application. TUTORIALS POINT Simply Easy Learning .java source file as shown above and compile it.

onLoad() This method is called before an object is initialized. These methods are callbacks from the session to the application. deleted or loaded. postFlush() This method is called after a flush has occurred and an object has been updated in memory. an object will be created and persisted. update operation. it must be saved back to the database. have been changed) during a flush i. Once the object has been changed.CHAPTER 18 Hibernate Interceptors A 1 2 3 4 s you have learnt that in Hibernate. 5 6 7 8 9 Hibernate Interceptor gives us total control over how an object will look to both the application and the database. TUTORIALS POINT Simply Easy Learning . Following is the list of all the methods available within the Interceptor interface: S. allowing the application to inspect and/or manipulate properties of a persistent object before it is saved. instantiate() This method is called when a persisted class is instantiated. preFlush() This method is called before a flush. isUnsaved() This method is called when an object is passed to the saveOrUpdate() method/ onDelete() This method is called before an object is deleted. Method and Description findDirty() This method is be called when the flush() method is called on a Session object. onFlushDirty() This method is called when Hibernate detects that an object is dirty (ie. This process continues until the next time the object is needed. onSave() This method is called before an object is saved. and it will be loaded from the persistent store.e. updated.N. Thus an object passes through different stages in its life cycle and Interceptor Interface provides methods which can be called at different stages to perform some required tasks.

Type[] types) { // do nothing } // This method is called when Employee object gets updated.Serializable. TUTORIALS POINT Simply Easy Learning .Type. String[] propertyNames. Type[] types) { if ( entity instanceof Employee ) { System. Object[] previousState. import org. return true. return true. Object[] currentState. import java. public class MyInterceptor extends EmptyInterceptor { private int updates. Following will be the simple steps to use Hibernate Interceptor functionality. Serializable id.println("Create Operation").println("preFlush"). Type[] types) { if ( entity instanceof Employee ) { System. private int loads. String[] propertyNames. Type[] types) { // do nothing return true.Iterator.println("Update Operation"). String[] propertyNames. You can implement more methods as per your requirements.out.io. import org.type. Serializable id. Serializable id.How to use Interceptors? To build an interceptor you can either implement Interceptor class directly or extend EmptyInterceptorclass. public void onDelete(Object entity.util. public boolean onFlushDirty(Object entity. private int creates. String[] propertyNames. } return false. import java. Object[] state. import java. } return false. } public boolean onLoad(Object entity.hibernate. public boolean onSave(Object entity.Date. Serializable id.out. Object[] state.EmptyInterceptor.hibernate.Transaction. Create Interceptors We will extend EmptyInterceptor in our example where Interceptor's method will be called automatically when Employee object is created and updated.hibernate. } // This method is called when Employee object gets created. } //called before commit into database public void preFlush(Iterator iterator) { System.util. import org.out. Object[] state.

} //called after committed into database public void postFlush(Iterator iterator) { System.out.println("postFlush"); } }

Create POJO Classes
Now let us modify a little bit our first example where we used EMPLOYEE table and Employee class to play with: public class Employee { private int id; private String firstName; private String lastName; private int salary; public Employee() {} public Employee(String fname, String lname, int salary) { this.firstName = fname; this.lastName = lname; this.salary = salary; } public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String first_name ) { this.firstName = first_name; } public String getLastName() { return lastName; } public void setLastName( String last_name ) { this.lastName = last_name; } public int getSalary() { return salary; } public void setSalary( int salary ) { this.salary = salary; } }

Create Database Tables
Second step would be creating tables in your database. There would be one table corresponding to each object you are willing to provide persistence. Consider above objects need to be stored and retrieved into the following RDBMS table: create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL,

TUTORIALS POINT Simply Easy Learning

last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) );

Create Mapping Configuration File
This step is to create a mapping file that instructs Hibernate how to map the defined class or classes to the database tables. <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description">
This class contains the employee detail.

</meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> </hibernate-mapping>

Create Application Class
Finally, we will create our application class with the main() method to run the application. Here it should be noted that while creating session object we used our Interceptor class as an argument.
import java.util.List; import java.util.Date; import java.util.Iterator; import import import import import org.hibernate.HibernateException; org.hibernate.Session; org.hibernate.Transaction; org.hibernate.SessionFactory; org.hibernate.cfg.Configuration;

public class ManageEmployee { private static SessionFactory factory; public static void main(String[] args) { try{ factory = new Configuration().configure().buildSessionFactory(); }catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex); }

TUTORIALS POINT Simply Easy Learning

ManageEmployee ME = new ManageEmployee(); /* Add few employee records in database */ Integer empID1 = ME.addEmployee("Zara", "Ali", 1000); Integer empID2 = ME.addEmployee("Daisy", "Das", 5000); Integer empID3 = ME.addEmployee("John", "Paul", 10000); /* List down all the employees */ ME.listEmployees(); /* Update employee's records */ ME.updateEmployee(empID1, 5000); /* Delete an employee from the database */ ME.deleteEmployee(empID2); /* List down new list of the employees */ ME.listEmployees(); } /* Method to CREATE an employee in the database */ public Integer addEmployee(String fname, String lname, int salary){ Session session = factory.openSession( new MyInterceptor() ); Transaction tx = null; Integer employeeID = null; try{ tx = session.beginTransaction(); Employee employee = new Employee(fname, lname, salary); employeeID = (Integer) session.save(employee); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } return employeeID; } /* Method to READ all the employees */ public void listEmployees( ){ Session session = factory.openSession( new MyInterceptor() ); Transaction tx = null; try{ tx = session.beginTransaction(); List employees = session.createQuery("FROM Employee").list(); for (Iterator iterator = employees.iterator(); iterator.hasNext();){ Employee employee = (Employee) iterator.next(); System.out.print("First Name: " + employee.getFirstName()); System.out.print(" Last Name: " + employee.getLastName()); System.out.println(" Salary: " + employee.getSalary()); } tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } } /* Method to UPDATE salary for an employee */ public void updateEmployee(Integer EmployeeID, int salary ){ Session session = factory.openSession( new MyInterceptor() ); Transaction tx = null; try{ tx = session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, EmployeeID); employee.setSalary( salary );

TUTORIALS POINT Simply Easy Learning

Create MyInterceptor.commit(). tx. }catch (HibernateException e) { if (tx!=null) tx. Transaction tx = null.class.java source file as shown above and compile it.hbm..session. e.VARIOUS LOG MESSAGES WILL DISPLAY HERE. }catch (HibernateException e) { if (tx!=null) tx. Execute ManageEmployee binary to run the program.xml mapping file as shown above. tx. EmployeeID).. e. You would get following result..java source file as shown above and compile it...close(). $java ManageEmployee .openSession( new MyInterceptor() ). Create ManageEmployee. Create Operation preFlush postFlush Create Operation preFlush postFlush Create Operation preFlush postFlush First Name: Zara Last Name: Ali Salary: 1000 First Name: Daisy Last Name: Das Salary: 5000 TUTORIALS POINT Simply Easy Learning .get(Employee. Create Employee.close(). try{ tx = session. } } /* Method to DELETE an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory...rollback().commit().delete(employee). } } } Compilation and Execution Here are the steps to compile and run the above mentioned application.beginTransaction(). }finally { session. Create Employee... Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution..update(employee).rollback(). session.xml configuration file as explained in configuration chapter..printStackTrace(). Employee employee = (Employee)session.cfg..java source file as shown above and compile it. and records would be created in EMPLOYEE table.       Create hibernate.printStackTrace().. }finally { session.

00 sec mysql> TUTORIALS POINT Simply Easy Learning . it should have following records: mysql> select * from EMPLOYEE. +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 29 | Zara | Ali | 5000 | | 31 | John | Paul | 10000 | +----+------------+-----------+--------+ 2 rows in set (0.First Name: John preFlush postFlush preFlush Update Operation postFlush preFlush postFlush First Name: Zara First Name: John preFlush postFlush Last Name: Paul Salary: 10000 Last Name: Ali Salary: 5000 Last Name: Paul Salary: 10000 If you check your EMPLOYEE table.

Sign up to vote on this title
UsefulNot useful