Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 72

Hibernate

--Ramadevi

Mandala

Introduction
What is Hibernate? Hibernate is a tool which is used for mapping a Java class and a database table. It provides data query and retrieval facilities and reduces development time spent in manual data handling. Hibernate is an open source framework, Object Relational Mapping (ORM) tool for java. ORM is a technique used for mapping data from an object model to a relational model. For instance from a Java class to an underlying database.

Introduction

Some of the advantages of using Hibernate includes:-.

 You'll be able to work with Java objects, instead of relational tables.  Your whole application won't need to change if either the objects or database schema change.  You won't have to worry about persistence details. Saving a whole object saves all of its fields and all of its attributes, even if they are objects or collections of objects.

Architecture
The High-Level Architecture of Hibernate can be explained with the help of the below diagram.

Architecture
The building blocks of the Hibernate Architecture includes:-

1.

Persistent Objects: Wherein the tables in the Relational Database are represented as Java Classes. Hibernate.properties or Configuration XML: It contains all configuration parameters required for the application to interact with the database. XML Mapping: As the name indicates, links the persistent objects with the underlying database.

2.

3.

Architecture
The components in a Hibernate Architecture include:-

 Connection Management
Connection management provided an efficient means of handling Database connections, which would otherwise be expensive, because a lot of resources frequently open and close Database Connections.

 Transaction Management
This service provides the ability for the user to execute more than one database query at a time.

 Object relational mapping

Object relational mapping as discussed earlier is the technique of mapping the data representation from an object model (i.e. the persistence classes) to a relational data model (tables in the underlying database).

Architecture
There are 2 main Architectural approaches in Hibernate: Lite Architecture Full Cream Architecture

Lite Architecture
Hibernate provides a lot of flexibility in its implementation. We can implement hibernate by utilizing only the Object Relational Mapping (ORM) technology ignoring Connection Management and Transaction Management features. This Architecture is commonly termed as the Lite architecture. The following slide depicts the Lite Architecture

Lite Architecture

Full Cream Architecture


The Full Cream architecture of Hibernate utilizes all the 3 components defined in the architecture. In this implementation Hibernate is responsible for.,

Establishing Connections with the Database. Executing multiple Transactions simultaneously. Implementation of Object Relational Mapping. The Full Cream architecture can be diagrammatically represented as follows:-

Full Cream Architecture

Full Cream Architecture


The building blocks of Hibernate can be explained as follows:-

Persistent Objects Single threaded objects containing the persistent state. They get associated with exactly one session. As soon as the session is closed, they will be detached and free to use in any application layer. Session Factory It allows the application to create a Hibernate session by reading Hibernate Configurations file hibernate.cfg.xml. It is the factory for the session and a Client for the Connection Provider.

Full Cream Architecture


 Session It is the main runtime interface between a Java application and Hibernate. It is a Single Threaded short lived object representing a conversation between the application and the persistent store. It wraps a JDBC connection, and is the Factory for Transaction.  Transaction Is a Single Threaded short lived object which specifies atomic units of work. A transaction abstracts the application from the underlying JDBC,JTA and JNDI. A session can have multiple transactions.

Full Cream Architecture


 Transaction Factory A factory for creating or instantiating transactions. Transaction Factory is not visible to the application, but can be extended / implemented by the developer.  Connection Provider A factory for JDBC connections. Manages a pool of connections made by various resources. Abstracts application from the underlying data source and Driver Manager. It is not visible to the application , but can be extended / implemented by the developer.

Hibernate Mappings

Prerequisites

There are 3 main pre-requisites in enabling an hibernate application:1. 2. 3. Hibernate Configuration Persistence class Hibernate Mapping

Hibernate Configuration
Hibernate is designed to operate in many different environments. So there are a large no of configuration parameters. All these are set in configuration files. There are 3 methods of setting the configuration:1.Use the setProperties() function of the Configuration class. 2. Place the hibernate.properties in a root directory of the classpath. 3. Include <property> element in hibernate.cfg.xml
Note: - The Configuration is intended as a startup-time object, to be discarded once a SessionFactory is created.

Example of hibernate.cfg.xml

<hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.url"> jdbc:oracle:thin:@ashopdb02b:1823:optest1</property> <property name="connection.username"> serviceuser</property> <property name="connection.password"> service</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> </session-factory> </hibernate-configuration>

Persistence Class

Persistent class is a POJO (Plain Old Java Object). It has a collection of getter and setter methods for each instance variable. Properties: It is the object Oriented Blueprint of the table to be persisted. The attributes of the table becomes the instance variables of the class. The data type of the instance variable becomes the domain of the attributes. The object of the persistence class represents the row of the table.

Example of Persistence class


Consider the following table class Student { String stid = null; String sname = null; Void setStid(String id) { Stid = id; } String getStid() { Return stid; } Void setSname(String name) { sname = name; } String getSname() { Return sname; } }

Student
Id Name

The persistence class is as follows:-

Hibernate Mapping

Hibernate Mapping is an xml file which provides the complete mapping from the persistence class to the table it represents. The elements in xml:1. <hibernate-mapping> 2. <class> 3. <id> 4. <property>

Format of Hibernate Mapping

Hibernate Mapping is the root element enclosing the other elements. A few attributes include:<hibernate-mapping schema="schemaName" catalog="catalogName" auto-import="true|false" package="package.name" />

<class> tag in Hibernate Mapping

The <class> element is used to map the class name to the table name. The element with the attributes are as follows:<class name="ClassName" table="tableName" discriminator-value="discriminator_value" schema="owner" catalog="catalog" />

<id> tag in Hibernate Mapping

This tag is used to map the primary key of the table to an instance variable of the class. <id name="propertyName" type="typename" column="column_name" <generator class="generatorClass"/> </id>

<id> tag in Hibernate Mapping

The optional <generator> element names a java class used to generate unique identifiers (or primary keys) for instances of the persistent class. Few built-in generators include: increment : generates unique identifiers when no other process is inserting data in the same table. sequence : uses the named sequence to generate the unique primary key. hilo : A table and column is specified in this case. The column specifies the next unique value for the key. seqhilo : A table, column and sequence name is specified. The next unique value is generated using the sequece on the specific column value.

<property> tag in Hibernate Mapping

This tag is used to map the other attributes of the table with the instance variables of the class. <property name="propertyName" column="column_name" type="typename" formula="arbitrary SQL expression" /> Formula attribute is an SQL expression that defines the value for a computed property. That is a property which doesnt have a column of their own.

<property> tag in Hibernate Mapping Hibernate Type :Hibernate types are used to map the Java property type to a JDBC type. For instance the java.lang.String in Java is varchar in JDBC. The hibernate type for this is string.
Mapping type Java type Standard SQL built-in type
integer int or java.lang.Integer INTEGER long long or java.lang.Long BIGINT short short or java.lang.Short SMALLINT float float or java.lang.Float FLOAT double double or java.lang.Double DOUBLE big_decimal java.math.BigDecimal NUMERIC character java.lang.String CHAR(1) string java.lang.String VARCHAR byte byte or java.lang.Byte TINYINT boolean boolean or java.lang.Boolean BIT yes_no boolean or java.lang.Boolean CHAR(1) ('Y' or 'N') true_false boolean or java.lang.Boolean CHAR(1) ('T' or 'F')

<composite-id> tag in Hibernate Mapping

If the composite keys of a table has to be mapped, the <composite-id> tag can be used. Format:<composite-id>

<key-property name=propertyName type=type column=columnName/> <key-property name=propertyName type=type column=columnName/> </composite-id>


The <key-property> tag specifies the set of columns which makes the composite key.

Example of Hibernate Mapping

Student.hbm.xml <hibernate-mapping> <class name=Student Table=Student> <id name = id column = Student_Id> <generator class=increment> </id> <property name=Sname column=Student_name type=string> </class> <hibernate-mapping>

Collection Mapping

A collection represents a group of objects, known as its elements. Collections in classes can also be mapped using hibernate and this is done using Collection mapping. The elements used are based on the interface used in the class. Like: Set List Map There can be a collection of values or entities For values, <element> tag is used For entities, <one-to-many> or <many-to-many> tag is used

Collection Mapping - Set

A Set can be thought of as any collection of distinct objects considered as a whole. Consider the two tables lecturer and Student
Student Lecturer
Lect_id Lect_subj Stud_id Stud_name Lect_id

Collection Mapping - Set Consider the case where 1 lecturer has many students:The following set tag is written in the hibernate mapping file of the Lecturer tag. <set name=setStudents> <key column=Lect_id> <one-to-many column=Lect_id class=Student> </set> The <Key> tag here represents the column in the Lecturer class which is a foreign key for the Student class. i.e. the key with which the two classes are linked. The <one-to-many> tag specifies the class with which the mapping is to be done and the foreign key column in the class.

Collection Mapping - Map

Car

Car_prop

Car_id

Car_Name

Car_id

Prop_name

Prop_value

A map is a simple name-value pair. They have a unique id. <class name="Car" table="Car"> ... <map name="Property"> <key column="car_id"/> <index column="Prop_name" type="string"/> <element column="Prop_value" type="string"/> </map> </class>

Collection Mapping - List


Member Team

Member_Id

Info

Idx

Parent_id

team_id

members

name

List is an ordered collection of entities. Consider the above tables. <class name=Team table=Team> <list name="members"> <key column=team_id" /> <index column="idx" /> <one-to-many class="member" /> </list> </class>

Association Mapping

There are different relations b/w tables: one-to-one One-to-many Many-to-one Many-to-many

All these relations can be mapped using Association mapping.

Association Mapping
One-to-Many Consider the Lecturer and Student example given above. Consider the case where 1 lecturer has many students. <set name=StudentsperLectId> <key column=Lect_id> <one-to-many class=Student> </set> The above tag is written in the Lecturer hibernate mapping file. It specifies that one Lect_id in the Lecturer table can have many values linked to in the Student table. The class attribute in the<one-to-many> tag specifies the class with which the Lecturer class is to be linked.

Association Mapping

Many-to-One Consider the same Lecturer and Student example. Now consider the reverse case. i.e. Many students can have the same Lecturer. <many-to-one name=LecturerSubjByLectId class=Lecturer column=Lect_id> The above tag is written in the Student hibernate mapping file. It specifies that many Students in the Student table can have the same Lect_id value linked to in the Lecturer table. The class attribute in the <manyto-one> tag specifies the class with which the Student class is to be linked. And the column attribute is the foreign key with which the link is done.

Association Mapping
Employee Empl_id Empl_name Manager Manager_id Empl_id

One-to-One
<class name=Manager table=Manager> <one-to-one name=EmployeeByEmplId" class=Employee"></one-to-one> </class> The above mapping specifies that there is a one to one relationship between the Employee and the Manager table. i.e. there is only 1 employee in the Employee table whose Empl_id is the one for a Manager_id.

Association Mapping
Student Language Stud_Lang Lang_id

Stud_id

Stud_name

Lang_id

Lang_name

Stud_id

Many-to-many <class name=Student table=Student> <set name=studLanguages" table=Stud_Lang"> <key column =Stud_id" /> <many-to-many column="Lang_id" class=Language" /> </set> </class> The above mapping specifies that many students can have more than 1 language and that a language can be taken up by many students. i.e. a many-to-many relationship.

Component Mapping

A component is a contained object which is persisted as a value type and not as an entity. For instance, say there are 2 classes: Person and Name. In Java, Person class can have an instance of Name as one of its variables (say name). This instance name is called a component. The component can be mapped in hibernate using Component Mapping. The element used for mapping is <component>.

Example for Component Mapping

Person Class public class Person { private Name name; private String id; public String getId() { return id; } private void setId(String id) { this.id=id; } public Name getName() { return name; } public void setName(Name name) { this.name = name; } }

Name Class public class Name { String first; String last; public String getFirst() { return first; } void setFirst(String first) { this.first = first; } public String getLast() { return last; } void setLast(String last) { this.last = last; } }

Hibernate Mapping <class name="eg.Person" table="person"> <id name="Key" column="pid" type="string"> <generator class="uuid"/> </id> <property name="birthday" type="date"/> <component name="Name" class="eg.Name"> <property name="initial"/> <property name="first"/> <property name="last"/> </component> </class>

Inheritance Mapping
Inheritance is the process that allows a class to acquire the properties of another class. This can be mapped in hibernate using Inheritance mapping. There are three basic inheritance mapping strategies: Table per class Table per subclass Table per concrete class

Inheritance Mapping
Consider the following hierarchy as an example
PAYMENT

CREDIT_CARD_PAYMENT CASH_PAYMENT

CHEQUE_PAYMENT

Inheritance Mapping

Table per class: Table per class strategy maps the whole class hierarchy into one table, and classes are differentiated by a discriminator column.
<class name="Payment" table="PAYMENT"> <id name="id" type="long" column="PAYMENT_ID"> <generator class="increment"/> </id> <discriminator column="PAYMENT_TYPE" type="string"/> <property name="amount" column="AMOUNT"/> ... <subclass name="CreditCardPayment" discriminator-value="CREDIT"> <property name="creditCardType" column="CCTYPE"/> ... </subclass> <subclass name="CashPayment" discriminator-value="CASH"> ... </subclass> <subclass name="ChequePayment" discriminator-value="CHEQUE"> ... </subclass> </class>

Inheritance Mapping

The Table per class strategy uses a <discriminator> element which specifies the column based on which the subclasses are differentiated. The element used to identify each subclass is:- <subclass> This element has an attribute discriminator-value, which specifies the value of the discriminator column for this subclass.

Inheritance Mapping
The <property> tags within each <subclass> specifies the properties which are of the subclass. For instance, consider the above example. The subclass CredtCardPayment has a discriminator-value as CREDIT which signifies that the rows in the table PAYMENT having the PAYMENT_TYPE value as CREDIT belongs to this subclass. The property creditCardType specifies the attribute of the CreditCardPayment subclass.

Inheritance Mapping
Table per subclass: Table per subclass strategy maps the base class into one table, and additional attributes in subclasses are mapped to additional tables joined back to the base table with foreign keys.
<class name="Payment" table="PAYMENT"> <id name="id" type="long" column="PAYMENT_ID"> <generator class=" increment "/> </id> <property name="amount" column="AMOUNT"/> ... <joined-subclass name="CreditCardPayment" table="CREDIT_PAYMENT"> <key column="PAYMENT_ID"/> <property name="creditCardType" column="CCTYPE"/> ... </joined-subclass> <joined-subclass name="CashPayment" table="CASH_PAYMENT"> <key column="PAYMENT_ID"/> ... </joined-subclass> <joined-subclass name="ChequePayment" table="CHEQUE_PAYMENT"> <key column="PAYMENT_ID"/> ... </joined-subclass> </class>

Inheritance Mapping
In this strategy, all the attributes of the parent class are present in 1 table and the attributes specific to the subclasses are present in individual tables. The mapping is done by using <joined-subclass> element. The subclasses are joined by a foreign key. The table attribute of the element signifies the table to which these subclasses are mapped. And the key tag specifies the foreign key of the subclass. For instance, in the above example, the attributes specific to the CreditCardPayment subclass is mapped to the CREDIT_PAYMENT table. The PAYMENT_ID column is the foreign key which joins the subclasses to the parent class. The <property> tag specifies the attributes of the respective tables.

Inheritance Mapping
Table per concrete class: In this strategy, each concrete class gets its own table, and all the inherited attributes are mapped to that table as well. The primary keys have to be shared between the tables.
<class name="Payment"> <id name="id" type="long" column="PAYMENT_ID"> <generator class="sequence"/> </id> <property name="amount" column="AMOUNT"/> ... <union-subclass name="CreditCardPayment" table="CREDIT_PAYMENT"> <property name="creditCardType" column="CCTYPE"/> ... </union-subclass> <union-subclass name="CashPayment" table="CASH_PAYMENT"> ... </union-subclass> <union-subclass name="ChequePayment" table="CHEQUE_PAYMENT"> ... </union-subclass> </class>

Inheritance Mapping
In this strategy, all the concrete classes have a table of its own. The mapping is done by using <union-subclass> element. All the subclasses have a common primary key. The table attribute of the element signifies the table to which these subclasses are mapped. For instance, in the above example, the attributes specific to the CreditCardPayment subclass is mapped to the CREDIT_PAYMENT table. The PAYMENT_ID column is the primary key of all the subclasses. The <property> tag specifies the attributes of the respective tables.

Hibernate Query Language

HQL Hibernate Query Language

Hibernate is equipped with a powerful query language of its own (HQL) to access Database

 HQL is used for building queries to find or filter data from DB. 
HQL is object oriented version of SQL.

Difference from SQL

 HQL queries returns java objects contrary to DB      

parameters returned by SQL HQL supports transparent and relational persistence HQL queries are database independent HQL supports advanced features like pagination, fetch joining with dynamic profiling, inner, outer and full joining HQL also supports usage of aggregate functions, ordering, grouping, sub queries and SQL function calls Most keywords in SQL are optional in HQL HQL is case sensitive

HQL Basics

Simplest Possible HQL query :from Employee Returns all Employee rows from data base in the form of Employee class objects which is mapped to the table Employee HQL is polymorphic which returns instances of all sub classes of a class Clauses :Select (Optional) from (Required except with Session and Filter) where ( Optional) Other : Order By, Group By, Having

   

How to write a simple HQL Query

Before writing the query we have to obtain an instance of hibernate session which is already opened at the start of the application while loading the configuration files. org.hibernate.Session defines the Session interface to hold the current session. Session session = HibernateSessionFactory.currentSession(); Now the session variable has an instance of the current session

Writing Simple Query

Interface org.hibernate.Query defines Query interface to hold the query written on the session Query query = session.createQuery(from Employee); List queryList = query.list(); Now the queryList contains list of objects returned by the query.

Simple HQL query where clause

where clause allows to narrow the list of instances returned. For example: from Employee where Employee.id = :empId returns All Employee with id as empId.

Simple HQL Query select clause

select clause picks the objects and properties to return in the query result set. select id from Employee This query will return the id of all Employee select id from Employee where Employee.salary :> 10000 This query returns the id of all Employee with salary greater than 10000

HQL polymorphic queries

HQL queries are polymorphic due to inheritance mapping. from Employee Will return the instances not only of Employee but also all the subclasses of Employee. HQL polymorphic queries will return instances of all the persistence classes that extend the class or implement the interface.

HQL Complex Queries

HQL supports sub queries and co related sub queries if underlying data base supports it. HQL supports all joining queries along with fetch joining. HQL allows handling of data with visibility rules using Hibernate Filters. Narrowing of Result Objects returned can be done by using Criteria Queries. Native SQL queries can be used to write queries in SQL format, retaining the benefits of transparent persistence. Named HQL queries can be created for reusability.

Criteria Queries

HQL has criteria queries to perform operations like narrowing the result set object which are returned based on the criteria defined at runtime. Interface org.hibernate.Criteria represents query against a particular class. Session is a factory for Criteria instances. Criteria crit = session.createCriteria(Employee.class); Required criteria can be given to the Criteria instance (crit)

Writing Criteria Queries

crit.add(Restrictions.like(name,an%); This criteria will fetch the names from Employee which starts only with a an. Criteria queries have functions to fetch selected pages of a large DB which is the basis of Pagination using hibernate.

Native SQL

Hibernate allows developers to write complex queries in the SQL format itself using native SQL interface, retaining the advantages of persistence. List queryList = session.createSQLQuery(select * from Employee).addEntity(Employee.class).list(); addEntity() will do the necessary mapping of Employee table to Employee class which results in returning generic objects.

Native SQL named queries

Named SQL queries can be defined in the mapping document and can be called in the application by query name which allows reusing of queries <sql-query name = persons> <return class = Employee.class/> Select person from Employee </sql-query> session.getNamedQuery(persons) Will return the results of the query in mapping file.

Hibernate Filter

Hibernate filter is a global named parameterized filer that may be enabled or disabled for a particular hibernate session. In order to use filters they must be defined and attached to appropriate mapping elements. To define a filter use <filter-def> element within <hibernate-mapping/> element. Filters can be enabled or disabled at session level.

Hibernate Filter
Narrowing result Objects Defining Filter : <filter-def name = myFilter> <filter- param name =myFilterParam type =string/> </filter-def> Attaching the filter to a class: <class name =myClass> <filter name = myFilter condition = :myFilterParam = My_Filtered_Column/> </class>

Hibernate Filter

Enabling or Disabling Filters: By default Filters are disabled. They have to be enabled on session level to use. session.enableFilter(myFilter) Will enable the filter myFilter for the Session session.

Hibernate in thick client app

Hibernate suits thick client applications better than JDBC or EJB because of relational and transparent persistence. Hibernate is a low weight replacement for CMP EJB . CMP EJB requires an EJB container to provide DB connection, transaction management and connection pooling while hibernate doesnt require a container for thick client applications.

Hibernate in Enterprise app

In Enterprise applications hibernate can be preferred over EJB due to the following reasons. All the DB transactions can be done using POJOs and mapping files and no need to follow complex format of writing Entity beans (remote and home interfaces)

Session and transaction management will also be done by hibernate frame work thus container job will be reduced.

Conclusion

Hibernate is a persistent, object relational and query service for java. Hibernate is highly recommended for modular 2 tier thick client applications because of its persistent and object relational mapping. Hibernate query service is highly efficient for faster DB access and is providing full support to object orientation. Advanced hibernate features results in wide areas of utilization.

Questions

THANK YOU

You might also like