Sei sulla pagina 1di 31

INTRODUCTION

Presented by : A.Aziz
aaziz@roadtodata.com

Date: 14th Dec, 2007


PART-1
 What is Hibernate
 How it works
 Architecture
 Main Components

PART-2 ( Example )
What is Hibernate?
 open source object/relational mapping
technology (ORM)
 easier to build robust,high-performance
database applications with Java.
 Hibernate applications are cheaper, more
portable, and more resilient to change
 Better system architecture (When separate database component from
the Business logic and the logic from the persistence mechanism you can more easily apply
changes to one part without influencing the other parts. ) – plug-and-play components
architecture
How it works

 Create Class Model


 Simple POJO (Plain Old Java Object)
 Create Data Model
 Create an XML mapping files (*.bhm.xml)
 Create Hibernate Configuration file (hibernate.cfg.xml)
 Call Hibernate APIs to load/store the persistent objects
 provides data query and retrieval facilities and can
significantly reduce development time otherwise spent with
manual data handling in SQL and JDBC ( support HQL, native SQL)
 Customised queries : insert-query, update-query, delete-
query, select-query and also can use Stored Procedures for
CRUD (Create, read, update and delete) operations
Architecture
Main Components
 POJOs (also called Java Beans)
 DAOs (Data Access objects)
 Mapping files (xml file like *.hbm.xml)
 Configration file (xml file “hibernate.cfg.xml”)
 Hibernate API
configuration files

 The first type of configuration file is named


hibernate.cfg.xml. On start up,Hibernate consults this
XML file for its operating properties,such as database
connection string and password,database
dialect,and mapping files locations. Hibernate searches
for this file on the class path
 The second type of configuration file is a mapping
description file (file extension *.hbm.xml) that instructs
Hibernate how to map data between a specific Java class
and one or more database tables
Configuration file (hibernate.cfg.xml)
<?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.username">sa</property>

<property name="connection.url">
jdbc:jtds:sqlserver://R2DDEV2:1433/hibernatertd
</property>

<property name="dialect">
org.hibernate.dialect.SQLServerDialect
</property>

<property name="connection.password">dev123</property>
<property name="connection.driver_class">
net.sourceforge.jtds.jdbc.Driver
</property>

</session-factory>

</hibernate-configuration>
Hibernate architecture main
components
 Connection Management :
Hibernate Connection management service provide efficient management of the
database connections. Database connection is the most expensive part of
interacting with the database as it requires a lot of resources of open and close the
database connection [Hibernate supports a variety of connection pooling mechanisms: c3p0, Apache DBCP, Proxool ]

 Session (org.hibernate.Session) :
A session is a connected object representing a conversation between the
application and the database. It wraps a JDBC connection and can be used to
maintain the transactions. It also holds a cache of persistent objects,used when
navigating the objects or looking up objects by identifier.

 Transaction (org.hibernate.Transaction) :
Transactions are used to denote an atomic unit of work that can be committed (saved)
or rolled back together. A transaction can be started by calling
session.beginTransaction() which actually uses the transaction mechanism of
underlying JDBC connection,JTA or CORBA

 Object relational mapping:


Object relational mapping is technique of mapping the data representation from an
object model to a relational data model. This part of the hibernate is used to select,
insert, update and delete the records form the underlying table. When we pass an
object to a Session.save() method, Hibernate reads the state of the variables of
that object and executes the necessary query.
Part-2 : Example

Customers Contacts Management


add,update,delete or search a customer and it’s
phone numbers in the database
Database Table Column Name Data Type Constraints

CUSTOMER_ID NUMBER PRIMARY KEY

FIRST_NAME TEXT NONE

LAST_NAME TEXT NONE

AGE NUMBER NONE

EMAIL TEXT NONE

CREATE TABLE CUSTOMER(


    USER_ID NUMBER PRIMARY KEY,
    FIRST_NAME VARCHAR(20),
    LAST_NAME VARCHAR(20),
    AGE NUMBER,
    EMAIL VARCHAR(40)
);
simple bean that represents this table

Package com.prtd.hibernate;
public class Customer implements java.io.Serializable {

/** The Constant serialVersionUID. */


private static final long serialVersionUID = 1L;

/** The customer id. */


private Integer customerId;

/** The first name. */


private String firstName; CREATE TABLE CUSTOMER(
    CUSTOMER_ID NUMBER PRIMARY KEY,
    FIRST_NAME VARCHAR(20),
/** The last name. */     LAST_NAME VARCHAR(20),
private String lastName;     AGE NUMBER,
    EMAIL VARCHAR(40)
/** The age. */ );
private Integer age;

/** The email. */


private String email;

…….
}
CREATE TABLE CUSTOMER(
    CUSTOMER_ID NUMBER PRIMARY KEY,
Mapping File (user.hbm.xml)
    FIRST_NAME VARCHAR(20),
    LAST_NAME VARCHAR(20), Package com.prtd.hibernate;
    AGE NUMBER, public class Customer {
    EMAIL VARCHAR(40)
); private Integer customerId= 0 ;
    private String firstName= "";
    private String lastName= "";
    private Integer age= 0;
    private String email= "";
<?xml version="1.0"?>
  <!DOCTYPE hibernate-mapping PUBLIC ……
}
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
 
  <hibernate-mapping>
 
      <class name=" com.prtd.hibernate.Customer" table="USERS" >
          <id name=“customerId" type="java.lang.Integer" column=“CUSTOMER_ID" >
                <generator class=“native" />
          </id>
          <property name="firstName" type="java.lang.String" column=“FIRST_NAME"
length="20" />
          <property name="lastName" type="java.lang.String" column=“LAST_NAME"
length="20" />
          <property name="age" type="java.lang.Integer" column=“AGE" length="-1" />
          <property name="email" type="java.lang.String" column=“EMAIL" length="40" />
      </class>
 
  </hibernate-mapping>
Configuration file (hibernate.cfg.xml)
<?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.username">sa</property>
<property name="connection.url">
jdbc:jtds:sqlserver://R2DDEV2:1433/hibernatertd
</property>
<property name="dialect">
org.hibernate.dialect.SQLServerDialect
</property>
<property name="connection.password">dev123</property>
<property name="connection.driver_class">
net.sourceforge.jtds.jdbc.Driver
</property>

<mapping resource="com/prtd/hibernate/Customer.hbm.xml" />

</session-factory>

</hibernate-configuration>
So far…
 we have written a Customer class (Customer.java) that we want to
persist and
 a mapping file (Customer.hbm.xml) that describes the relationship of
each of the attributes of the class to the database columns.
 We have also configured the Hibernate configuration file hibernate.cfg
.xml) to use the Customer.hbm.xml.

 Now it is the time to write a DAO that can perform different operations on
the User object.
Data Access Object (DAO)

package com.prtd.hibernate;
import org.hibernate.Session;
import com.prtd.hibernate.Customer;

public class CustomerDAO extends BaseHibernateDAO {

public void save(Customer transientInstance) {


try {

Session session = getSession();

Transaction tx = session.beginTransaction();

session.save(transientInstance);

tx.commit();

System.out.println("Saved Successfully");

} catch (RuntimeException re) {

System.out.println(“Errror : "+re);
}
}
}
TestClient
package com.prtd.hibernate.test;
import java.util.Iterator;
import com.prtd.hibernate.Customer;
import com.prtd.hibernate.CustomerDAO;
import com.prtd.hibernate.PhoneNumbers;

public class TestClient {

public static void main(String[] args) {

// DAOs
CustomerDAO customerDAO = new CustomerDAO();

// Customer
Customer customer = new Customer();

// customer properties
customer.setFirstName("ABC");
customer.setLastName("XYZ");
customer.setAge(22);
customer.setEmail("any@roadtodata.com");

// save customer
customerDAO.save(customer);
Output..

Customer Saved Successfully

ID : 42
Name : ABC XYZ
Email : any@roadtodata.com
Mapping
 Association mapping
Mapping Associations
 Association is a relationship of one class
to another class known as
'relationships' in database terminology
 One-to-one
 One-to-many
 Many-to-many
Example
Table: PHONE_NUMBERS

CREATE TABLE PHONE_NUMBERS (


ID int NOT NULL ,
PHONE varchar (20) COLLATE NOT NULL ,
NUMBER_TYPE varchar (10) COLLATE
CUSTOMER_ID int NOT NULL
)
Customer.java
Package com.prtd.hibernate;
public class Customer {

private Integer customerId= 0 ;


    private String firstName= "";
    private String lastName= "";
    private Integer age= 0;
    private String email= "";

/** The phone numberses. */


private Set<PhoneNumbers> phoneNumberses = new HashSet<PhoneNumbers>(0);

……
}

PhoneNumbers.java
package com.prtd.hibernate;

public class PhoneNumbers implements java.io.Serializable {

private Integer id;


private Customer customer;
private String phone;
private String numberType;
……
}
Customer.hbm.xml
<hibernate-mapping>
<class name="com.prtd.hibernate.Customer" table="CUSTOMER" schema="dbo"
catalog="hibernatertd">

<id name="customerId" type="java.lang.Integer">


<column name="CUSTOMER_ID" />
<generator class="native" />
</id>
<property name="firstName" type="java.lang.String">
<column name="FIRST_NAME" length="20" not-null="true" />
</property>
<property name="lastName" type="java.lang.String">
<column name="LAST_NAME" length="20" not-null="true" />
</property>
<property name="age" type="java.lang.Integer">
<column name="AGE" not-null="true" />
</property>
<property name="email" type="java.lang.String">
<column name="EMAIl" length="40" not-null="true" />
</property>
<set name="phoneNumberses" inverse="true" cascade="all">
<key>
<column name="CUSTOMER_ID" not-null="true" />
</key>
<one-to-many class="com.prtd.hibernate.PhoneNumbers" />
</set>
</class>
PhoneNumbers.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.prtd.hibernate.PhoneNumbers" table="PHONE_NUMBERS" schema="dbo"
catalog="hibernatertd">

<id name="id" type="java.lang.Integer"> package


<column name="ID" /> com.prtd.hibernate;
<generator class="native" />
</id> public class PhoneNumbers
implements
<property name="phone" type="java.lang.String"> java.io.Serializable {
<column name="PHONE" length="20" not-null="true" />
</property>
private Integer id;
private Customer customer;
private String phone;
<property name="numberType" type="java.lang.String">
private String numberType;
<column name="NUMBER_TYPE" length="10" not-null="true" />
…..
</property>

<many-to-one name="customer" class="com.prtd.hibernate.Customer“>


<column name="CUSTOMER_ID" not-null="true" />
</many-to-one>

</class>
</hibernate-mapping>
TestClient
package com.prtd.hibernate.test;
import java.util.Iterator;
import com.prtd.hibernate.Customer;
import com.prtd.hibernate.CustomerDAO;
import com.prtd.hibernate.PhoneNumbers;

public class TestClient {

public static void main(String[] args) {

// DAOs
CustomerDAO customerDAO = new CustomerDAO();

// Customer
Customer customer = new Customer();

// customer properties
customer.setFirstName("ABC");
customer.setLastName("XYZ");
customer.setAge(22);
customer.setEmail("any@roadtodata.com");

// Home phone
PhoneNumbers phoneNumber1 = new PhoneNumbers();
phoneNumber1.setNumberType("Home");
phoneNumber1.setPhone("020734567654");
phoneNumber1.setCustomer(customer);
// Office phone
PhoneNumbers phoneNumber2 = new PhoneNumbers();
phoneNumber2.setNumberType("Office");
phoneNumber2.setPhone("07816762345");
phoneNumber2.setCustomer(customer);

// Other phone
PhoneNumbers phoneNumber3 = new PhoneNumbers();
phoneNumber3.setNumberType("Other");
phoneNumber3.setPhone("0852675234");
phoneNumber3.setCustomer(customer); // for customer

// customer phone numbers


customer.getPhoneNumberses().add(phoneNumber1); // home phone
customer.getPhoneNumberses().add(phoneNumber2); // office phone
customer.getPhoneNumberses().add(phoneNumber3); // other phone

// save customer
customerDAO.save(customer);

// Find Customer
Customer foundCustomer = customerDAO.findById(customer.getCustomerId());

System.out.print("\nCustomer found \nID : "+foundCustomer.getCustomerId());

System.out.println("\nName : "+foundCustomer.getFirstName()+" "+foundCustomer.getLastName());


System.out.println("Email : "+foundCustomer.getEmail());

Iterator<PhoneNumbers> phonesNumbers = foundCustomer.getPhoneNumberses().iterator();

System.out.print("\nPhone Numbers : ");


while(phonesNumbers.hasNext())
{
PhoneNumbers foundPhoneNumber = phonesNumbers.next();
System.out.println("\n\t"+foundPhoneNumber.getNumberType()+" : "+foundPhoneNumber.getPhone());
}

System.out.print("\n");

// Delete
customerDAO.delete(foundCustomer);
Output

Customer Saved Successfully

Customer found
ID : 42
Name : ABC XYZ
Email : any@roadtodata.com

Phone Numbers :
Home : 020734567654

Office : 07816762345

Other : 0852675234

Customer Deleted Successfully


Recourses

 Example (source code & documentation)


 \\rotoda\Development\prtd_wip\Introduction_to_hibernate\Introduction_To_Hibernate_PRTD

 Documentation (\\rotoda\Development\prtd_wip\Introduction_to_hibernate\doc )

 WEB
 http://www.hibernate.org/hib_docs/reference/en/html/tutorial.html
Questions?
END

Thanks for your time.

Potrebbero piacerti anche