SlideShare a Scribd company logo
1 of 17
An Introduction to Hibernate
Object-Relational Mapping Technique


Hibernate provides mapping between:
 Java Classes and the database tables.
 The Java data types and SQL data types.
Basic Architecture
Hibernate Configuration File
<?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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
   <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
   <property name="hibernate.connection.url">jdbc:mysql://localhost:3307/libms</property>
   <property name="hibernate.connection.username">root</property>
<!-- JDBC connection pool (use the built-in) -->
      <property name="connection.pool_size">1</property>
<!-- Enable Hibernate's automatic session context management -->
      <property name="current_session_context_class">thread</property>
      <!-- Disable the second-level cache -->
      <property
     name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
      <!-- Echo all executed SQL to stouts -->
      <property name="show_sql">true</property>
      <!-- Drop and re-create the database schema on startup -->
      <property name="hbm2ddl.auto">update</property>
<mapping resource="com/myapp/struts/hbm/Staff.hbm.xml"/>
<mapping resource="com/myapp/struts/hbm/Department.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Hibernate Mapping File
                           <?xml version="1.0"?>
                           <!DOCTYPE hibernate-mapping PUBLIC
                                "-//Hibernate/Hibernate Mapping DTD 3.0//
Field Name     Data Type   EN"
                                "http://www.hibernate.org/dtd/hibernate-
Staff_id       VARCHAR(1   mapping-3.0.dtd">
                           <hibernate-mapping>
               0)           <class name="com.myapp.struts.beans.Staff"
                           table=“Staff" catalog="libms">
Staff_name     VARCHAR(3        <id name="StaffId" type="string">
               0)                   <column name=“Staff_id" length=“10" />
                                    <generator class="assigned" />

Staff_Depart   VARCHAR(3        </id>
                                <property name=“StaffName"
ment           0)          type="string">
                                    <column name=“Staff_name"
                           length="30" not-null="true" />
                                </property>
                                <property name=“StaffDep" type="string">
                                   <column name=“Staff_Department"
                           length=“30" />
                           </class>
public class Employee implements java.io.Serializable {
                                                     private String StaffId;
                                                     private String StaffName;
POJO                                                 private String StaffDep;
                                                    public Staff() {
<?xml version="1.0"?>                               }
                                                    public Staff(String id, String name) {
<!DOCTYPE hibernate-mapping PUBLIC
                                                       this. StaffId = id;
     "-//Hibernate/Hibernate Mapping DTD               this. StaffName = name;
3.0//EN"                                            }
                                                    public Staff(String id, String name, String dep) {
     "http://www.hibernate.org/dtd/hibernate-
                                                      this.id = id;
mapping-3.0.dtd">                                     this.name = name;
<hibernate-mapping>                                   this. StaffDep = dep;
 <class name="com.myapp.struts.beans.Staff"         }

table=“Staff" catalog="libms">
                                                    public String getStaffId() {
     <id name="StaffId" type="string">                return this. StaffId;
         <column name=“Staff_id" length=“10" />     }

         <generator class="assigned" />             public void setStaffId(String id) {
     </id>                                             this. StaffId = id;
                                                    }
     <property name=“StaffName" type="string">
                                                    public String StaffName() {
         <column name=“Staff_name" length="30"         return this. StaffName;
not-null="true" />                                  }
                                                    public void set StaffName(String name) {
     </property>
                                                       this. StaffName = name;
     <property name=“StaffDep" type="string">       }
        <column name=“Staff_Department"           public String get StaffDep() {
                                                       return this. StaffDep;
length=“30" />
                                                    }
</class>                                            public void set StaffDep(String department) {
</hibernate-mapping>                                   this. StaffDep = department;
                                                    }
Basic APIs

   SessionFactory (org.hibernate.SessionFactory)
   Session (org.hibernate.Session)
   Persistent objects and collections
   Transient and detached objects and collections
   Transaction (org.hibernate.Transaction)
   ConnectionProvider
    (org.hibernate.connection.ConnectionProvider)
   TransactionFactory (org.hibernate.TransactionFactory)
SessionFactory (org.hibernate.SessionFactory)




   A SessionFactory is an immutable, thread-safe object, intended
    to be shared by all application threads. It is created once,
    usually on application startup, from a Configuration instance.

   A org.hibernate.SessionFactory is used to obtain
    org.hibernate.Session instances.

   HibernateUtil helper class that takes care of startup and makes
    accessing the org.hibernate.SessionFactory more convenient.
HibernateUtil class
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
  private static final SessionFactory sessionFactory = buildSessionFactory();
  private static SessionFactory buildSessionFactory() {
     try {
        // Create the SessionFactory from hibernate.cfg.xml
        return 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 SessionFactory getSessionFactory() {
     return sessionFactory;
  }
}
Session (org.hibernate.Session)


   A single-threaded, short-lived object representing a
    conversation between the application and the persistent store.
    Wraps a JDBC java.sql.Connection.
   Used for a single request, a conversation or a single unit of
    work.
   A Session will not obtain a JDBC Connection, or a Datasource,
    unless it is needed. It will not consume any resources until
    used.
Persistent, Transient and Detached objects


   Transient - an object is transient if it has just been instantiated using
    the new operator, and it is not associated with a Hibernate Session.
   Persistent - a persistent instance has a representation in the database
    and an identifier value. It might just have been saved or loaded,
    however, it is by definition in the scope of a Session. Hibernate will
    detect any changes made to an object in persistent state and
    synchronize the state with the database when the unit of work
    completes.
   Detached - a detached instance is an object that has been persistent,
    but its Session has been closed. The reference to the object is still
    valid, of course, and the detached instance might even be modified in
    this state. A detached instance can be reattached to a new Session at
    a later point in time, making it (and all the modifications) persistent
    again.
Transaction (org.hibernate.Transaction)


    A single-threaded, short-lived object used by the application to specify
    atomic units of work. It abstracts the application from the underlying
    JDBC, JTA or CORBA transaction.
   Security is provided by this API.
ConnectionProvider
  (org.hibernate.connection.ConnectionProvider)



   A factory for, and pool of, JDBC connections. It abstracts the
    application from underlying javax.sql.DataSource or
    java.sql.DriverManager.
Extended Architecture
JSP              Action Mapping          Struts-config.xml                  Success/Failure
                                                                                                 JSP

    Fetch Values

Action Form
                           Refers
                                                               Action Class
                   Get Parameters


                                             Set Parameters
                                                               Return Values

                                           POJO
                                     Invoke Methods
                                                          Update POJO



                                                        DAO Beans

                                                         Interacts


                                                          JDBC

                                                          Interacts

                                                       DATABASE
This was a short introduction of hibernate.
           Want to know more?
Query me @ mohdzeeshansafi@yahoo.com

      Special Thanks to Mr Asif Iqbal

More Related Content

What's hot

An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring DataOliver Gierke
 
究極のコントローラを目指す
究極のコントローラを目指す究極のコントローラを目指す
究極のコントローラを目指すYasuo Harada
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)lennartkats
 
Metrics for example Java project
Metrics for example Java projectMetrics for example Java project
Metrics for example Java projectZarko Acimovic
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQLddiers
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf Conference
 
Software architecture2008 ejbql-quickref
Software architecture2008 ejbql-quickrefSoftware architecture2008 ejbql-quickref
Software architecture2008 ejbql-quickrefjaiverlh
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기Arawn Park
 
Models Best Practices (ZF MVC)
Models Best Practices (ZF MVC)Models Best Practices (ZF MVC)
Models Best Practices (ZF MVC)eddiejaoude
 
Semantic code transformations in MetaJS
Semantic code transformations in MetaJSSemantic code transformations in MetaJS
Semantic code transformations in MetaJSDmytro Dogadailo
 
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...Cloudera, Inc.
 
A Spring Data’s Guide to Persistence
A Spring Data’s Guide to PersistenceA Spring Data’s Guide to Persistence
A Spring Data’s Guide to PersistenceVMware Tanzu
 
First java-server-faces-tutorial-en
First java-server-faces-tutorial-enFirst java-server-faces-tutorial-en
First java-server-faces-tutorial-entechbed
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیMohammad Reza Kamalifard
 

What's hot (18)

An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
究極のコントローラを目指す
究極のコントローラを目指す究極のコントローラを目指す
究極のコントローラを目指す
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
 
Metrics for example Java project
Metrics for example Java projectMetrics for example Java project
Metrics for example Java project
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
 
Software architecture2008 ejbql-quickref
Software architecture2008 ejbql-quickrefSoftware architecture2008 ejbql-quickref
Software architecture2008 ejbql-quickref
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
Enterprise js pratices
Enterprise js praticesEnterprise js pratices
Enterprise js pratices
 
Models Best Practices (ZF MVC)
Models Best Practices (ZF MVC)Models Best Practices (ZF MVC)
Models Best Practices (ZF MVC)
 
Semantic code transformations in MetaJS
Semantic code transformations in MetaJSSemantic code transformations in MetaJS
Semantic code transformations in MetaJS
 
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
 
XML-Javascript
XML-JavascriptXML-Javascript
XML-Javascript
 
A Spring Data’s Guide to Persistence
A Spring Data’s Guide to PersistenceA Spring Data’s Guide to Persistence
A Spring Data’s Guide to Persistence
 
First java-server-faces-tutorial-en
First java-server-faces-tutorial-enFirst java-server-faces-tutorial-en
First java-server-faces-tutorial-en
 
hibernate
hibernatehibernate
hibernate
 
Phactory
PhactoryPhactory
Phactory
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
 

Viewers also liked

02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate IntroductionRanjan Kumar
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkRaveendra R
 
THE WORLDS NO.1 BLACK MAGIC EXPERT WITH POWERFUL LOVE SPELLS +27631229624
THE WORLDS NO.1 BLACK MAGIC EXPERT WITH POWERFUL LOVE SPELLS  +27631229624 THE WORLDS NO.1 BLACK MAGIC EXPERT WITH POWERFUL LOVE SPELLS  +27631229624
THE WORLDS NO.1 BLACK MAGIC EXPERT WITH POWERFUL LOVE SPELLS +27631229624 mamaalphah alpha
 
Hibernate an introduction
Hibernate   an introductionHibernate   an introduction
Hibernate an introductionjoseluismms
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An IntroductionNguyen Cao
 
Introduction To Hibernate
Introduction To HibernateIntroduction To Hibernate
Introduction To Hibernateashishkulkarni
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentationManav Prasad
 
Molly's Digital Poetry Book
Molly's Digital Poetry BookMolly's Digital Poetry Book
Molly's Digital Poetry Bookmmhummel
 
Seven Factors to Lose Weight the Healthy Way
Seven Factors to Lose Weight the Healthy WaySeven Factors to Lose Weight the Healthy Way
Seven Factors to Lose Weight the Healthy Waydabnel
 
Acute Compartment syndrome
Acute Compartment syndromeAcute Compartment syndrome
Acute Compartment syndromeAsi-oqua Bassey
 
Mld35 engine manual from sdshobby.net
Mld35 engine manual from sdshobby.netMld35 engine manual from sdshobby.net
Mld35 engine manual from sdshobby.netsdshobby
 
Programr Brief Overview
Programr Brief OverviewProgramr Brief Overview
Programr Brief Overview_programr
 
การประยุกต์จิตวิทยาเพื่อการเรียนรู้
การประยุกต์จิตวิทยาเพื่อการเรียนรู้การประยุกต์จิตวิทยาเพื่อการเรียนรู้
การประยุกต์จิตวิทยาเพื่อการเรียนรู้Mai Amino
 
การประยุกต์จิตวิทยาเพื่อการเรียนรู้
การประยุกต์จิตวิทยาเพื่อการเรียนรู้การประยุกต์จิตวิทยาเพื่อการเรียนรู้
การประยุกต์จิตวิทยาเพื่อการเรียนรู้Mai Amino
 

Viewers also liked (20)

02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Hibernate
HibernateHibernate
Hibernate
 
THE WORLDS NO.1 BLACK MAGIC EXPERT WITH POWERFUL LOVE SPELLS +27631229624
THE WORLDS NO.1 BLACK MAGIC EXPERT WITH POWERFUL LOVE SPELLS  +27631229624 THE WORLDS NO.1 BLACK MAGIC EXPERT WITH POWERFUL LOVE SPELLS  +27631229624
THE WORLDS NO.1 BLACK MAGIC EXPERT WITH POWERFUL LOVE SPELLS +27631229624
 
Hibernate an introduction
Hibernate   an introductionHibernate   an introduction
Hibernate an introduction
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An Introduction
 
Introduction To Hibernate
Introduction To HibernateIntroduction To Hibernate
Introduction To Hibernate
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Molly's Digital Poetry Book
Molly's Digital Poetry BookMolly's Digital Poetry Book
Molly's Digital Poetry Book
 
Seven Factors to Lose Weight the Healthy Way
Seven Factors to Lose Weight the Healthy WaySeven Factors to Lose Weight the Healthy Way
Seven Factors to Lose Weight the Healthy Way
 
Acute Compartment syndrome
Acute Compartment syndromeAcute Compartment syndrome
Acute Compartment syndrome
 
Mld35 engine manual from sdshobby.net
Mld35 engine manual from sdshobby.netMld35 engine manual from sdshobby.net
Mld35 engine manual from sdshobby.net
 
TACPOWER
TACPOWERTACPOWER
TACPOWER
 
Programr Brief Overview
Programr Brief OverviewProgramr Brief Overview
Programr Brief Overview
 
Al Asbab Profile 4
Al Asbab Profile 4Al Asbab Profile 4
Al Asbab Profile 4
 
การประยุกต์จิตวิทยาเพื่อการเรียนรู้
การประยุกต์จิตวิทยาเพื่อการเรียนรู้การประยุกต์จิตวิทยาเพื่อการเรียนรู้
การประยุกต์จิตวิทยาเพื่อการเรียนรู้
 
Hazon
HazonHazon
Hazon
 
การประยุกต์จิตวิทยาเพื่อการเรียนรู้
การประยุกต์จิตวิทยาเพื่อการเรียนรู้การประยุกต์จิตวิทยาเพื่อการเรียนรู้
การประยุกต์จิตวิทยาเพื่อการเรียนรู้
 
Issue1
Issue1Issue1
Issue1
 

Similar to Introduction to hibernate

Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
Struts database access
Struts database accessStruts database access
Struts database accessAbass Ndiaye
 
Hibernate
HibernateHibernate
Hibernateksain
 
Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012hwilming
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2Haroon Idrees
 
Hadoop Integration in Cassandra
Hadoop Integration in CassandraHadoop Integration in Cassandra
Hadoop Integration in CassandraJairam Chandar
 
MVC on the server and on the client
MVC on the server and on the clientMVC on the server and on the client
MVC on the server and on the clientSebastiano Armeli
 
How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF Luc Bors
 
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...jaxconf
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashBret Little
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Oliver Gierke
 
The Past Year in Spring for Apache Geode
The Past Year in Spring for Apache GeodeThe Past Year in Spring for Apache Geode
The Past Year in Spring for Apache GeodeVMware Tanzu
 
Spring data iii
Spring data iiiSpring data iii
Spring data iii명철 강
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.pptDrMeenakshiS
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...탑크리에듀(구로디지털단지역3번출구 2분거리)
 

Similar to Introduction to hibernate (20)

Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
Hibernate
Hibernate Hibernate
Hibernate
 
Struts database access
Struts database accessStruts database access
Struts database access
 
Hibernate
HibernateHibernate
Hibernate
 
Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
Hadoop Integration in Cassandra
Hadoop Integration in CassandraHadoop Integration in Cassandra
Hadoop Integration in Cassandra
 
MVC on the server and on the client
MVC on the server and on the clientMVC on the server and on the client
MVC on the server and on the client
 
How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF
 
How te bring common UI patterns to ADF
How te bring common UI patterns to ADFHow te bring common UI patterns to ADF
How te bring common UI patterns to ADF
 
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!
 
The Past Year in Spring for Apache Geode
The Past Year in Spring for Apache GeodeThe Past Year in Spring for Apache Geode
The Past Year in Spring for Apache Geode
 
Spring data iii
Spring data iiiSpring data iii
Spring data iii
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
 
JNDI
JNDIJNDI
JNDI
 

Recently uploaded

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 

Recently uploaded (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 

Introduction to hibernate

  • 1. An Introduction to Hibernate
  • 2. Object-Relational Mapping Technique Hibernate provides mapping between:  Java Classes and the database tables.  The Java data types and SQL data types.
  • 4.
  • 5. Hibernate Configuration File <?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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3307/libms</property> <property name="hibernate.connection.username">root</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stouts --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <mapping resource="com/myapp/struts/hbm/Staff.hbm.xml"/> <mapping resource="com/myapp/struts/hbm/Department.hbm.xml"/> </session-factory> </hibernate-configuration>
  • 6. Hibernate Mapping File <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0// Field Name Data Type EN" "http://www.hibernate.org/dtd/hibernate- Staff_id VARCHAR(1 mapping-3.0.dtd"> <hibernate-mapping> 0) <class name="com.myapp.struts.beans.Staff" table=“Staff" catalog="libms"> Staff_name VARCHAR(3 <id name="StaffId" type="string"> 0) <column name=“Staff_id" length=“10" /> <generator class="assigned" /> Staff_Depart VARCHAR(3 </id> <property name=“StaffName" ment 0) type="string"> <column name=“Staff_name" length="30" not-null="true" /> </property> <property name=“StaffDep" type="string"> <column name=“Staff_Department" length=“30" /> </class>
  • 7. public class Employee implements java.io.Serializable { private String StaffId; private String StaffName; POJO private String StaffDep; public Staff() { <?xml version="1.0"?> } public Staff(String id, String name) { <!DOCTYPE hibernate-mapping PUBLIC this. StaffId = id; "-//Hibernate/Hibernate Mapping DTD this. StaffName = name; 3.0//EN" } public Staff(String id, String name, String dep) { "http://www.hibernate.org/dtd/hibernate- this.id = id; mapping-3.0.dtd"> this.name = name; <hibernate-mapping> this. StaffDep = dep; <class name="com.myapp.struts.beans.Staff" } table=“Staff" catalog="libms"> public String getStaffId() { <id name="StaffId" type="string"> return this. StaffId; <column name=“Staff_id" length=“10" /> } <generator class="assigned" /> public void setStaffId(String id) { </id> this. StaffId = id; } <property name=“StaffName" type="string"> public String StaffName() { <column name=“Staff_name" length="30" return this. StaffName; not-null="true" /> } public void set StaffName(String name) { </property> this. StaffName = name; <property name=“StaffDep" type="string"> } <column name=“Staff_Department" public String get StaffDep() { return this. StaffDep; length=“30" /> } </class> public void set StaffDep(String department) { </hibernate-mapping> this. StaffDep = department; }
  • 8. Basic APIs  SessionFactory (org.hibernate.SessionFactory)  Session (org.hibernate.Session)  Persistent objects and collections  Transient and detached objects and collections  Transaction (org.hibernate.Transaction)  ConnectionProvider (org.hibernate.connection.ConnectionProvider)  TransactionFactory (org.hibernate.TransactionFactory)
  • 9. SessionFactory (org.hibernate.SessionFactory)  A SessionFactory is an immutable, thread-safe object, intended to be shared by all application threads. It is created once, usually on application startup, from a Configuration instance.  A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances.  HibernateUtil helper class that takes care of startup and makes accessing the org.hibernate.SessionFactory more convenient.
  • 10. HibernateUtil class import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return 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 SessionFactory getSessionFactory() { return sessionFactory; } }
  • 11. Session (org.hibernate.Session)  A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC java.sql.Connection.  Used for a single request, a conversation or a single unit of work.  A Session will not obtain a JDBC Connection, or a Datasource, unless it is needed. It will not consume any resources until used.
  • 12. Persistent, Transient and Detached objects  Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session.  Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes.  Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again.
  • 13. Transaction (org.hibernate.Transaction)  A single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction.  Security is provided by this API.
  • 14. ConnectionProvider (org.hibernate.connection.ConnectionProvider)  A factory for, and pool of, JDBC connections. It abstracts the application from underlying javax.sql.DataSource or java.sql.DriverManager.
  • 16. JSP Action Mapping Struts-config.xml Success/Failure JSP Fetch Values Action Form Refers Action Class Get Parameters Set Parameters Return Values POJO Invoke Methods Update POJO DAO Beans Interacts JDBC Interacts DATABASE
  • 17. This was a short introduction of hibernate. Want to know more? Query me @ mohdzeeshansafi@yahoo.com Special Thanks to Mr Asif Iqbal