Hibernate 3

31
INTRODUCTION Presented by : A.Aziz [email protected] Date: 14 th Dec, 2007

description

Hibernate 3 tutorial: ORM Hibernate

Transcript of Hibernate 3

Page 1: Hibernate 3

INTRODUCTION

Presented by : [email protected]

Date: 14th Dec, 2007

Page 2: Hibernate 3

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

PART-2 ( Example )

Page 3: Hibernate 3

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

Page 4: Hibernate 3

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

Page 5: Hibernate 3

Architecture

Page 6: Hibernate 3

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

Page 7: Hibernate 3

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

Page 8: Hibernate 3

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>

Page 9: Hibernate 3

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.

Page 10: Hibernate 3

Part-2 : Example

Customers Contacts Managementadd,update,delete or search a customer and it’s

phone numbers in the database

Page 11: Hibernate 3

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));

Database Table

Page 12: Hibernate 3

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;

/** The last name. */private String lastName;

/** The age. */private Integer age;

/** The email. */private String email;

…….}

CREATE TABLE CUSTOMER(    CUSTOMER_ID NUMBER PRIMARY KEY,    FIRST_NAME VARCHAR(20),    LAST_NAME VARCHAR(20),    AGE NUMBER,    EMAIL VARCHAR(40));

Page 13: Hibernate 3

Mapping File (user.hbm.xml)

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

CREATE TABLE CUSTOMER(    CUSTOMER_ID NUMBER PRIMARY KEY,    FIRST_NAME VARCHAR(20),    LAST_NAME VARCHAR(20),    AGE NUMBER,    EMAIL VARCHAR(40));

Package com.prtd.hibernate;public class Customer {

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

……}

Page 14: Hibernate 3

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>

Page 15: Hibernate 3

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.

Page 16: Hibernate 3

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);}

}}

Page 17: Hibernate 3

TestClientpackage 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) {

// DAOsCustomerDAO customerDAO = new CustomerDAO();

// CustomerCustomer customer = new Customer();

// customer propertiescustomer.setFirstName("ABC");customer.setLastName("XYZ");customer.setAge(22);customer.setEmail("[email protected]");

// save customercustomerDAO.save(customer);

Page 18: Hibernate 3

Customer Saved Successfully

ID : 42Name : ABC XYZEmail : [email protected]

Output..

Page 19: Hibernate 3

Mapping Association mapping

Page 20: Hibernate 3

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

Page 21: Hibernate 3

Example

Page 22: Hibernate 3

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

)

Page 23: Hibernate 3

Customer.javaPackage 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.javapackage com.prtd.hibernate;

public class PhoneNumbers implements java.io.Serializable {

private Integer id;private Customer customer;private String phone;private String numberType;

……}

Page 24: Hibernate 3

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></hibernate-mapping>

Page 25: Hibernate 3

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"> <column name="ID" /> <generator class="native" /> </id> <property name="phone" type="java.lang.String"> <column name="PHONE" length="20" not-null="true" /> </property> <property name="numberType" type="java.lang.String"> <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>

package com.prtd.hibernate;

public class PhoneNumbers implements java.io.Serializable {

private Integer id;private Customer customer;private String phone;private String numberType;…..

}

Page 26: Hibernate 3

TestClientpackage 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) {

// DAOsCustomerDAO customerDAO = new CustomerDAO();

// CustomerCustomer customer = new Customer();

// customer propertiescustomer.setFirstName("ABC");customer.setLastName("XYZ");customer.setAge(22);customer.setEmail("[email protected]");

// Home phonePhoneNumbers phoneNumber1 = new PhoneNumbers();phoneNumber1.setNumberType("Home");phoneNumber1.setPhone("020734567654");phoneNumber1.setCustomer(customer);

Page 27: Hibernate 3

// Office phonePhoneNumbers phoneNumber2 = new PhoneNumbers();phoneNumber2.setNumberType("Office");phoneNumber2.setPhone("07816762345");phoneNumber2.setCustomer(customer);

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

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

// save customercustomerDAO.save(customer);

// Find CustomerCustomer 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");

// DeletecustomerDAO.delete(foundCustomer);

}

}

Page 28: Hibernate 3

Output

Customer Saved Successfully

Customer found ID : 42Name : ABC XYZEmail : [email protected]

Phone Numbers : Home : 020734567654

Office : 07816762345

Other : 0852675234

Customer Deleted Successfully

Page 29: Hibernate 3

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

Page 30: Hibernate 3

Questions?

Page 31: Hibernate 3

Thanks for your time.

END