0% found this document useful (0 votes)
102 views

Hibernate

Hibernate is an open source object-relational mapping tool for Java that provides a framework for mapping an object-oriented domain model to a traditional relational database. It supports direct SQL queries, object inheritance, collections, associations, and more. Hibernate uses XML configuration files or an API to define mappings from Java classes to database tables. It then manages the database interaction so developers can interact with objects rather than directly with SQL statements or JDBC.

Uploaded by

avinashf02
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views

Hibernate

Hibernate is an open source object-relational mapping tool for Java that provides a framework for mapping an object-oriented domain model to a traditional relational database. It supports direct SQL queries, object inheritance, collections, associations, and more. Hibernate uses XML configuration files or an API to define mappings from Java classes to database tables. It then manages the database interaction so developers can interact with objects rather than directly with SQL statements or JDBC.

Uploaded by

avinashf02
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 68

HIBERNATE

INTRODUCTION
Working with object-oriented software and a relational database is time consuming Need to bridge relational and object-oriented technologies, or to replace one with the other However the gap between the two is one of the hard facts Object-relational mapping tool is required to bridge this gap

What is ORM?

The term Object-Relational Mapping (ORM) refers to the technique of mapping a data representation, from an object model, to a relational data model with SQL-based schema
3

Hibernate Overview
Hibernate is a full-featured, open source Object-Relational mapping framework Hibernate is similar to EJB CMP/CMR (container-managedpersistence / container-managed-relationships) and JDO (Java Data Objects) Hibernate focuses entirely on OR mapping for relational databases and includes more features than most commercial products Hibernate helps in developing persistent classes following objectoriented idiom including: association, inheritance, polymorphism, composition, and collections Hibernate allows to express queries in its own portable SQL extension (HQL) As well as in native SQL, or with an object-oriented Criteria and Example API Hibernate is a Professional Open Source project
4

Hibernate Architecture

Hibernate Architecture Explained


Persistent Objects: Wherein the tables in the Relational Database are represented as Java Classes. Hibernate.properties: 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.
6

Hibernate Architectural Approaches


Hibernate is flexible and supports several approaches Following are the 2 main Architectural approaches in Hibernate: Lite Architecture Full Cream Architecture

Hibernate Lite Architecture

Hibernate Full Cream Architecture

Definition of Hibernate Objects


SessionFactory (net.sf.hibernate.SessionFactory)
A threadsafe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProvider. Might hold an optional (second-level) cache of data that is reusable between transactions, at a process- or cluster-level.

Session (net.sf.hibernate.Session)
A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC connection. Factory for Transaction. Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier.

Persistent Objects and Collections


Short-lived, single threaded objects containing persistent state and business function. These might be ordinary JavaBeans/POJOs, the only special thing about them is that they are currently associated with (exactly one) Session. As soon as the Session is closed, they will be detached and free to use in any application layer (e.g. directly as data transfer objects to and from presentation).

Transient Objects and Collections


Instances of persistent classes that are not currently associated with a Session. They may have been instantiated by the application and not (yet) 10 persisted or they may have been instantiated by a closed Session.

Definition of Hibernate Objects


Transaction (net.sf.hibernate.Transaction)
(Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases.

ConnectionProvider (net.sf.hibernate.connection.ConnectionProvider)
(Optional) A factory for (and pool of) JDBC connections. Abstracts application from underlying Datasource or DriverManager. Not exposed to application, but can be extended/implemented by the developer.

TransactionFactory (net.sf.hibernate.TransactionFactory)
(Optional) A factory for Transaction instances. Not exposed to the application, but can be extended/implemented by the developer.

11

Configuring Hibernate
Two types of Configurations:
Programmatic Configuration XML configuration

Programmatic Configuration
An instance of org.hibernate.cfg.Configuration represents an entire set of mappings of an application's Java types to an SQL database. The Configuration is used to build an immutable SessionFactory. The mappings are compiled from various XML mapping files. When all mappings have been parsed by the Configuration, the application must obtain a factory for Session instances. This factory is intended to be shared by all application threads.

12

Programmatic Configuration
Sample hibernate.properties file:
hibernate.connection.driver_class = oracle.jdbc.driver.OracleDriver hibernate.connection.url = jdbc:oracle:thin@localhost:1521:mydatabase hibernate.connection.username = myuser hibernate.connection.password = secret hibernate.dialect = net.sf.hibernate.dialect.Oracle9Dialect

Programmatically loading of the hibernate.properties:

Configuration cfg = new Configuration(); cfg.getProperties("hibernate.properties"); cfg.addResource("Customer.hbm.xml"); cfg.setProperty(Environment.SHOW_SQL, "true"); SessionFactory sessionFactory = = cfg.buildSessionFactory();
13

XML Configuration
An alternative approach to configuration - hibernate.cfg.xml. Used as a replacement for the hibernate.properties file or, if both are present, to override the properties. Configuration file is by default expected to be in the root of the CLASSPATH.
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.url">jdbc:oracle:thin@localhost:1521:mydatabase</property> <property name="connection.username">myuser</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="dialect">net.sf.hibernate.dialect.Oracle9Dialect</property> <property name="connection.password">secret</property> <property name="hibernate.show_sql">true</property> <!-- mapping files --> <mapping resource="Customer.hbm.xml" /> </session-factory> </hibernate-configuration>

14

XML Configuration
Loading of the XML configuration
Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); SessionFactory sessionFactory = = cfg.buildSessionFactory();

15

Creating Persistent Classes


Persistent classes are classes in an application that implement the entities of the business problem. Not all instances of a persistent class are considered to be in the persistent state, an instance may instead be transient or detached. Hibernate works best if the persistent classes follow some simple rules, also known as the Plain Old Java Object (POJO) programming model. All persistent classes must have a default constructor (which may be non-public) so Hibernate can instantiate them using Constructor.newInstance(). So, most POJOs are Hibernate-compatible without any changes.
16

Hibernate Basic O/R Mapping Elements


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>

17

Hibernate O/R Mapping Root Element


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" />
18

Basic O/R Mapping <class> Element


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" />
19

Basic O/R Mapping <id> Elements


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>

20

Basic O/R Mapping - <generator> element


The optional <generator> element names a java class used to generate unique identifiers (or primary keys) for instances of the persistent class. Few builtin 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 sequence on the specific column value.
21

Basic O/R Mapping <property> element


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. 22

Hibernate Basic O/R 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
integer long short float double big_decimal character string byte boolean yes_no true_false

Java type

Standard SQL built-in type


INTEGER BIGINT SMALLINT FLOAT DOUBLE NUMERIC CHAR(1) VARCHAR TINYINT BIT CHAR(1) ('Y' or 'N') CHAR(1) ('T' or 'F')

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

23

Hibernate Basic O/R Mapping


<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"> <hibernate-mapping> <class name="com.sample.entity.Customer" table="Customer"> <id name="customerId" column="customer_id" type="long"> <generator class="assigned"/> </id> <property name="name" not-null="true"/> <property name="birthdate" type="date"/> </class> </hibernate-mapping>

24

Hibernate Basic O/R Mapping Elements


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.
25

Retrieving/Storing Java Object


Retrieving Data:
Session session = sessionFactory.getSession(); Customer customerObj = (Customer) session.load(Customer.class, new Long(id)); or Customer customerObj = (Customer) session.get(Customer.class, new Long(id));

Storing Data:
Customer customerObj = new Customer(); customerObj.setCustomerId(id); customerObj.setBirthDate(date); customerObj.setName(Shiv); Session session = sessionFactory.getSession(); Transaction transaction = session.beginTansaction(); session.save(customerObj); transaction.commit();

26

Hibernate 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
27

Hibernate 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
Lecturer Student

Lect_id

Lect_subj
Stud_id Stud_name Lect_id

28

Hibernate 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.
29

Hibernate Collection Mapping - Map


Car Car_id Car_Name Car_prop 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>
30

Hibernate Collection Mapping - List


Member Member_Id Info Idx Parent_id Team 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>
31

Hibernate Association Mapping


one-to-one association SQL Scripts
<hibernate-mapping> <class name="eg.Parent"> <id name="id"> <generator class="sequence"/> </id> <one-to-one column=parent_id class="eg.Child"/> </class> <class name="eg.Child"> <id name="id"> <generator class="sequence"/> </id> <property name="name"/> </class> </hibernate-mapping>

create table parent ( id bigint not null primary key )


create table child ( id bigint not null primary key, name varchar(255), parent_id bigint ) alter table child add constraint childfk0 (parent_id) references parent If the scenario is: one parent-one child

32

Hibernate Association Mapping


one-to-many association SQL Scripts
<hibernate-mapping> <class name="eg.Parent"> <id name="id"> <generator class="sequence"/> </id> <set name="children" lazy="true"> <key column="parent_id"/> <one-to-many class="eg.Child"/> </set> </class> <class name="eg.Child"> <id name="id"> <generator class="sequence"/> </id> <property name="name"/> </class> </hibernate-mapping>

create table parent ( id bigint not null primary key )


create table child ( id bigint not null primary key, name varchar(255), parent_id bigint ) alter table child add constraint childfk0 (parent_id) references parent

33

Hibernate Association Mapping


many-to-one association SQL Scripts
<hibernate-mapping> <class name="eg.Parent"> create table parent ( id bigint not null primary key ) <id name="id"> <generator class="sequence"/> create table child ( id bigint not null primary key, </id> name varchar(255), parent_id bigint not null) <set name="children" lazy="true"> <key column="parent_id"/> alter table child add constraint childfk0 (parent_id) <one-to-many class="eg.Child"/> references parent </set> </class> <class name="eg.Child"> <id name="id"> <generator class="sequence"/> </id> <property name="name"/> <many-to-one name="parent" class="eg.Parent" column="parent_id" not-null="true"/> </class> 34 </hibernate-mapping>

Hibernate Association Mapping


many-to-many association SQL Scripts
<hibernate-mapping> <class name="eg.Parent"> <id name="id"> <generator class="sequence"/> </id> <set name="children" lazy="true table=childset> <key column="parent_id"/> <many-to-many class="eg.Child column=child_id/> </set> </class> <class name="eg.Child"> <id name="id"> <generator class="sequence"/> </id> <property name="name"/> </class> </hibernate-mapping>

create table parent ( id bigint not null primary key )


create table child ( id bigint not null primary key, name varchar(255) ) create table childset ( parent_id bigint not null, child_id bigint not null, primary key ( parent_id, child_id ) ) alter table childset add constraint childsetfk0 (parent_id) references parent

alter table childset add constraint childsetfk1 (child_id) references child

35

Hibernate Association Mapping


Saving/Retrieving Data:
Parent parentObj = new Parent(); Child childObj = new Child(); .... Set children = new HashSet(); children.add(childObj); parentObj.setChildren(children); session.save(parentObj); children = parentObj.getChildren();

36

Hibernate Component Mapping


Mapping a dependant object using Component Mapping: <class name="eg.Person" table="person"> <id name="Key" column="pid" type="string"> <generator class="uuid.hex"/> </id> <property name="birthday" type="date"/> <component name="Name" class="eg.Name"> <!-- class attribute optional --> <property name="initial"/> <property name="first"/> <property name="last"/> </component> </class>

Note: The person table would have the columns pid, birthday, initial, first and last.

37

Hibernate Component Mapping


Mapping a collection of dependant objects using Component Mapping:

<set name="someNames" table="some_names" lazy="true"> <key column="id"/> <composite-element class="eg.Name"> <!-- class attribute required --> <property name="initial"/> <property name="first"/> <property name="last"/> </composite-element> </set>

38

Hibernate Component Mapping


Components as Map Indices
The <composite-index> element lets you map a component class as the key of a Map

Components as Composite Identifiers


<class name="eg.Foo" table"FOOS"> <composite-id name="compId" class="eg.FooCompositeID"> <key-property name="string"/> <key-property name="short"/> <key-property name="date" column="date_" type="date"/> </composite-id> <property name="name"/> .... </class>
39

Hibernate 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 hierarchy Table per subclass Table per concrete class

40

Hibernate Inheritance Mapping


Table per Class hierarchy:
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>

41

Hibernate 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. 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.
42

Hibernate 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>

43

Hibernate 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.
44

Hibernate 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> 45

Hibernate 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.

46

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. 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.
47

Hibernate Query Language


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

48

Writing Simple HQL


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

49

Writing Simple HQL where clause


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.


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.
50

Writing Simple HQL 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
51

Writing Simple HQL


queries

Polymorphic

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.
52

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.
53

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); crit.setMaxResults(50); List cats = crit.list();

Required criteria can be given to the Criteria instance (crit)

54

Criteria Queries Narrowing the result set


List cats = sess.createCriteria(Cat.class) .add( Expression.like("name", "Fritz%") ) .add( Expression.between("weight", minWeight, maxWeight) ) .list(); List cats = sess.createCriteria(Cat.class) .add( Expression.like("name", "Fritz%") ) .add( Expression.or( Expression.eq( "age", new Integer(0) ), Expression.isNull("age") ) ) .list();
55

Example Queries
Example example = Example.create(cat) .excludeZeroes() //exclude zero valued properties .excludeProperty("color") //exclude the property named "color" .ignoreCase() //perform case insensitive string comparisons .enableLike(); //use like for string comparisons

List results = session.createCriteria(Cat.class) .add(example) .list();

56

Native SQL
Hibernate allows developers to write complex queries in the SQL format itself using native SQL interface, retaining the advantages of persistence. Query sqlQuery = sess.createSQLQuery("select {cat.*} from cats {cat}", "cat", Cat.class); sqlQuery.setMaxResults(50); List cats = sqlQuery.list(); 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.
57

Native SQL
String sql = "select cat.originalId as {cat.id}, " + " cat.mateid as {cat.mate}, cat.sex as {cat.sex}, + " cat.weight*10 as {cat.weight}, cat.name as {cat.name}" + " from cat_log cat where {cat.mate} = :catId" List loggedCats = sess.createSQLQuery(sql, "cat", Cat.class) . setLong("catId", catId) .list();

58

Named SQL Query


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
List people = sess.getNamedQuery("mySqlQuery") .setMaxResults(50) .list();

The named SQL query is in the mapping file


<sql-query name = persons> <return class = Employee.class/> Select person from Employee </sql-query>
59

Hibernate Filters
Hibernate filter is a global named parameterized filter 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.

60

Hibernate Filters Narrowing the result set


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> 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.

61

import org.hibernate.*; import org.hibernate.cfg.*;

Hibernate Session Management / Thread-safe Session object

public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { // Create the SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static final ThreadLocal session = new ThreadLocal(); public static Session currentSession() throws HibernateException { Session s = (Session) session.get(); // Open a new Session, if this Thread has none yet if (s == null) { s = sessionFactory.openSession(); session.set(s); } return s; } public static void closeSession() throws HibernateException { Session s = (Session) session.get(); session.set(null); if (s != null) s.close(); } }

62

Object States

63

Transactions and Concurrency


You should observe the following practices when creating Hibernate Sessions:
Never create more than one concurrent Session or Transaction instance per database connection. Be extremely careful when creating more than one Session per database per transaction. The Session itself keeps track of updates made to loaded objects, so a different Session might see stale data. The Session is not threadsafe! Never access the same Session in two concurrent threads. A Session is usually only a single unit-of-work!
64

Transactions and Concurrency


Long session with automatic versioning
A single Session instance and its persistent instances are used for the whole application transaction.

Many sessions with automatic versioning


Each interaction with the persistent store occurs in a new Session.

Application version checking


Each interaction with the database occurs in a new Session that reloads all persistent instances from the database before manipulating them. This approach forces the application to carry out its own version checking to ensure application transaction isolation.
65

Hibernate Performance Tuning


Lists, maps and sets are the most efficient collections to update One shot delete Using Proxy for Lazy Loading Using batch fetching Cache Mapping

66

References
Websites:
http://www.hibernate.org http://hibernate.bluemars.net/hib_docs/referen ce/en/html/index.html

Books:
Hibernate Reference Document Version: 3.0.5 Hibernate in Action - By Christian Bauer and Galvin King
67

Happy O/R Mapping with Hibernate!

You might also like