Sunteți pe pagina 1din 12

Hibernate

Hibernate is one of the most efficient ORM implementations in java.


ORM is a system that provides solution for the various problems in mapping the
object model to the relational model.
Why ORM?
Most of the enterprise applications create its own object model to represent the
domain data.
Moreover most of these applications persist the data into RDMS. It is identified
that the complex object model does not perfectly match with the relational model
and the code implementing the gap to map object model to relational model is
known as ORM.
Key features of Hibernate:
1. It supports POJOs as the persistent objects.
2. Supports java bean style properties to persist, that means, any java object
supporting java bean style properties can be configured to hibernate for
persisting into the database.
3. Dual layer cache support.
4. Supports an object oriented query language(SQL).
5. Supports for API based approach to query the object that is using criterion
API.
6. Supports for lazy loading.
Hibernate Architecture:
The following are top level elements of hibernate system.
1.
2.
3.
4.
5.
6.
7.

Configuration Object
Session Factory
Session
Transaction
Query
Criteria
Hibernate Configuration & Mapping Xml Documents.

Understanding the Hibernate Configurations:


Hibernate configurations can be configured in 3 styles.
1. Properties file
2. Xml document
3. API style.
Hibernate Configurations:
1.
2.
3.
4.
5.
6.

DB Configuration.
Pool Management Properties.
Transaction Properties.
Cache Configuration.
SQL Dialect.
Logging.

All the above configurations are represented by org.hibernate.cfg.Configuration.


The hibernate config properties can be loaded into the configuration object using
any of the 3 styles.
1. Properties file:
The configuration object locates hibernate.properties file from the class path by
default while instantiation of this object.
2. Xml Document:
We use cfg.configure() to load the config details from the hibernate cfg xml
document into the configuration object.
Configuration conf = new Configuration();
conf.configure();
This loads the config details from hibernate.cfg.xml.
We can use the overloaded configure method to specify the cfg xml document file
location.
conf.configure(mydb.cfg.xml);

3. API style:
The org.hibernate.cfg.Configuration object supports various methods to set the
hibernate config properties such as addClass(), addResource().
Properties File can be used to configure common properties between multiple
databases that we want to access.
The following are few properties supported by hibernate.
1. connection.driver_class specifies the qualified name of the JDBC driver
class used by hibernate to establish the connection to database.
2. connection.url
3. connection.username
4. connection.password
5. show_sql
6. dialect
We want to add hibernate. Prefix to all these properties while describing them in
properties file.
Hibernate Mapping:
We can configure the mapping details in 2 different styles,
1. Xml style
Create the hibernate xml mapping document.
Load the mapping definition into the configuration object.
2. Annotation style.
Implementing Hibernate Persistent Object:
Hibernate supports POJOs as persistent objects, that means, we dont have to use
hibernate API for implementing the persistent object.
However, we have to follow few rules listed below while implementing the
hibernate persistent object.
The persistent properties should be implemented in java bean style, i.e., a
setter and getter method.
Should support no argument constructor.

The persistent object and the properties should be non-final in the case if the
object is configured for lazy loading.
Implements equals and hash code method.
Example 1:
package com.acc.hibernate;
public class Employee
{
private int empId;
private String empName;
private String designation;
//setters & getters
}
Employee.hbm.xml:
<hibernate-mapping>
<class name = com.acc.hibernate.Employee table = emp_tab>
<id name = empId column = empid>
<generator class = assigned/>
</id>
<property name = empName column = ename/>
<property name = designation />
</class>
</hibernate-mapping>
Hibernate.cfg.xml:

<hibernate-configuration>
<session-factory>
<property name
</property>

connection.driver_class>oracle.jdbc.driver.OracleDriver

<property name = connection.url>jdbc:oracle:thin:@localhost:1521:xe


</property>
<property name = connection.username>system</property>
<property name = connection.password>site</property>
<property name = dialect>org.hibernate.dialect.Oracle9Dialect
</property>
<property name = show_sql>false</property>
<mapping resource = Employee.hbm.xml/>
</session-factory>
</hibernate-configuration>

package com.acc.hibernate;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateTestCase
{
public static void main(String args[])
{
Configuration conf = new Configuration().configure();

SessionFactory sf = conf.buildSessionFactory();
Session session = sf.openSession();
Employee emp = (Employee)session.load(Employee.class,101);
System.out.println(emp.getEmpId());
System.out.println(emp.getEmpName());
System.out.println(emp.getDesignation());
session.close();
}
}
To run this example set the classpath to the jar files,

hibernate3.jar
log4j.jar
commons-logging.jar
dom4j.jar
cglib.jar
ehcache.jar
jta.jar
ojdbc14.jar
commons-dbcp.jar
commons-collections.jar
commons-pool.jar

Problem of Granularity:
Public class PersonalDetails
{
Private int empNo;
Private String fname,lname,email;

Private Address addr;


//setters & getters
}
Package com.acc.hibernate;
Public class Address
{
Private String hno,street,city,state,country;
Private int pin;
//setters & getters
}
PersonalDetails.hbm.xml:
<hibernate-mapping package = com.acc.hibernate>
<class name = PersonalDetails table = emp_personal_details>
<id name = empno>
<generator class = assigned/>
</id>
<property name = fname/>
<property name = lname/>
<property name = email/>
<component name = addr class = Address>
<property name = hno/>
<property name = street/>
<property name = city/>

<property name = state/>


<property name = country/>
<property name = pin/>
</component>
</class>
</hibernate-mapping>
Public class hibernatetestcase2
{
Public static void main(String args[])
{
Configuration conf = new Configuration().configure();
SessionFactory sf = conf.buildSessionFactory();
Session session = sf.openSession();
PersonalDetails
pd
(PersonalDetails)session.load(PersonalDetails.class,101);

System.out.println(pd.getFname());
System.out.println(pd.getAddr().getStreet());
session.close();
}
}
http://www.vaannila.com/hibernate/hibernate-example/hibernate-mapping-one-toone-1.html
follow this above link to see how one-to-one relationship is established using
hibernate.

<many-to-one>:
The name attribute specifies the property name to represent this relationship. The
column attribute specifies the database column name that is mapped to the identity
of the other end object of this relation.
<one-to-many>:
<set name= emps>
<key column = dno/>
<one-to-many class = Employee/>
</set>
Lazy attribute:
This supports true/false.
Specifying true describes not to load the relationship data when the relationship
property is accessed and false describes to eagerly load the relationship data.
Cascade attribute:
Hibernate supports cascade option to describe about the save, update and delete
operations with respect to the relationship. The following values are supported by
this property,
1. none
This is default taken by hibernate, if this property is not used.
This describes to ignore the relation objects for insert, update and delete
operations.
2. save_update
Specifies to consider the relationship property for insert and update operations
only.
3. Delete

Specifies to consider the relationship property for delete operation only.


4. All
This describes hibernate to cascade the relation objects for all the DML
operations.
The object mapped to hibernate can be into the following 3 states,
1. Persistent object
The objects under the control of the hibernate session, i.e. , into the cache are
referred as persistent objects.
2. Transient object
These objects are not managed by the hibernate session.
3. Detached object
Previously part of session but now detached.
Session.Update() : updates the record if record is available. But does not insert
the record if record is not available {based on the id value}

Session.merge(): updates the record if record is available. Otherwise inserts the


new record.
Session.update() does not return persistent state pojo object that representing
the record that has been updated where as session.merge() returns that object
Session.save() ----returns Serializable {apart from saving the record into the
database returns the id that is generated}
Session.persist()--- returns void {saves the object into db but doesnt return any
id}

Problem of sub-types:

Table per class hierarchy


package com.acc.hib;
public abstract class Employee
{
Private int empNo;
Private String emailed,name,mobile;
//setters & getters
}
----------------------------------------------Package com.acc.hib;
Class SalariedEmployee extends Employee
{
Private double sal;
//setters & getters
}
---------------------------------------------Package com.acc.hib;
Public class HourlyEmployee extends Employee
{
Private int rate_per_hour;
Private int max_hours_per_day;
//setters & getters
}

Employee.hbm.xml:
<hibernate-mapping package = com.acc.hib>
<class name = Employee table = emp_details>
<id name = empNo>
<generator class = increment/>
</id>
<discriminator column = emp_type/>
<property name = name/>
<property name = emailId/>
<property name = mobile/>
<subclass name = SalariedEmployee discriminator-value = salaried>
<property name = salary column = sal/>
</subclass>
<subclass name = HourlyEmployee discriminator-value = hourly>
<property name = max_hours_per_day/>
<property name = rate_per_hour/>
</subclass>
</class>
</hibernate-mapping>
In this case the common and specific data elements in the hierarchy are saved
into a single table however the table could be added with an additional column
that describes about the type of the object the record is representing.
The additional column emp_type that is designed to describe the object type
is referred as discriminator column.

S-ar putea să vă placă și