SlideShare a Scribd company logo
1 of 27
Download to read offline
Hibernate
 Object/Relational Mapping and Transparent
Object Persistence for Java and SQL Databases
Facts about Hibernate

True transparent persistence

Query language aligned with SQL

Does not use byte code enhancement

Free/open source
What is Hibernate?

** Hibernate is a powerful, ultra-high performance object/relational
persistence and query service for Java. Hibernate lets you develop
persistent objects following common Java idiom - including association,
inheritance, polymorphism, composition and the Java collections
framework. Extremely fine-grained, richly typed object models are
possible. The Hibernate Query Language, designed as a quot;minimalquot;
object-oriented extension to SQL, provides an elegant bridge between
the object and relational worlds. Hibernate is now the most popular
ORM solution for Java.

                                                 ** http://www.hibernate.org
Object-relational
impedance mismatch

Object databases are not the answer

Application Objects cannot be easily
persisted to relational databases

Similar to the putting square peg into round
hole
Object/Relational
    Mapping (ORM)

Mapping application objects to relational
database

Solution for infamous object-relational
impedance mismatch

Finally application can focus on objects
Transparent Persistence


 Persist application objects without knowing
 what relational database is the target

 Persist application objects without
 “flattening” code weaved in and out of
 business logic
Query Service


Ability to retrieve sets of data based on
criteria

Aggregate operations like count, sum, min,
max, etc.
Why use Hibernate?
Simple to get up and running

Transparent Persistence achieved using
Reflection

Isn’t intrusive to the build/deploy process

Persistence objects can follow common java
idioms: Association, Inheritance,
Polymorphism, Composition, Collections

In most cases Java objects do not even know
they can be persisted
Why use Hibernate
       cont

Java developer can focus on object modeling

Feels much more natural than Entity Beans or
JDBC coding

Query mechanism closely resembles SQL so
learning curve is low
What makes up a
Hibernate application?
Standard domain objects defined in Java as
POJO’s, nothing more.

Hibernate mapping file

Hibernate configuration file

Hibernate Runtime

Database
What is missing from a
Hibernate application?

 Flattening logic in Java code to conform to
 relational database design

 Inflation logic to resurrect Java object from
 persistent store

 Database specific tweaks
Hibernate Classes
SessionFactory - One instance per app.
Creates Sessions. Consumer of hibernate
configuration file.

Session - Conversation between application
and Hibernate

Transaction Factory - Creates transactions to
be used by application

Transaction - Wraps transaction
implementation(JTA, JDBC)
Hibernate Sample App

Standard Struts Web Application

Deployed on JBoss

Persisted to MySQL database

All hand coded, didn’t use automated tools to
generate Java classes, DDL, or mapping files

Disclaimer: Made simple stupid on purpose
DVD Library


Functions

  Add DVD’s to your collection

  Output your collection
Separation of
      Responsibility


                  Persistence
         Struts
JSP
                    classes
         Action
DVD POJO
                                   NOTE:
public class DVD {                 I transform
  private Long id;                 the DVDForm Bean to DVD
                                   prior to persisting for
  private String name;             added flexibility
  private String url;

    public Long getId() {
      return id;
    }

    public void setId(Long id) {
       this.id = id;
    }
    ..
    ..
}
Hibernate Mapping File
     DVD.hbm.xml
  <?xml version=quot;1.0quot;?>
  <!DOCTYPE hibernate-mapping PUBLIC
        quot;-//Hibernate/Hibernate Mapping DTD 2.0//ENquot;
        quot;http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtdquot;>

  <hibernate-mapping>
      <class name=quot;com.shoesobjects.DVDquot; table=quot;dvdlistquot;>
          <id name=quot;idquot; column=quot;idquot; type=quot;java.lang.Longquot; unsaved-value=quot;nullquot;>
              <generator class=quot;nativequot;/>
          </id>
          <property name=quot;namequot; column=quot;namequot; type=quot;java.lang.Stringquot; not-null=quot;truequot;/>
          <property name=quot;urlquot; column=quot;urlquot; type=quot;java.lang.Stringquot;/>
      </class>
  </hibernate-mapping>
Hibernate.properties
 #################
 ### Platforms ########
 #################


 ## JNDI Datasource
 hibernate.connection.datasource java:/DVDDB


 ## MySQL
 hibernate.dialect net.sf.hibernate.dialect.MySQLDialect
 hibernate.connection.driver_class org.gjt.mm.mysql.Driver
 hibernate.connection.driver_class com.mysql.jdbc.Driver
DVDService Class

public void updateDVD(DVD dvd) {
       Session session = ConnectionFactory.getInstance().getSession();

       try {
           Transaction tx = session.beginTransaction();
           session.update(dvd);
           tx.commit();
           session.flush();
       } catch (HibernateException e) {
          tx.rollback();
       } finally {
           // Cleanup
       }

   }
ConnectionFactory
public class ConnectionFactory {

   private static ConnectionFactory instance = null;
   private SessionFactory sessionFactory = null;

   private ConnectionFactory() {
       try {
           Configuration cfg = new Configuration().addClass(DVD.class);
           sessionFactory = cfg.buildSessionFactory();
       } catch (Exception e) {
           // Do something useful
       }
   }


   public Session getSession() {
      Session session = null;
      try {
          session = sessionFactory.openSession();
      } catch (HibernateException e) {
          // Do Something useful
      }
      return session;
   }
ConnectionFactory
        Improved
public class ConnectionFactory {

   private static ConnectionFactory instance = null;
   private SessionFactory sessionFactory = null;

   private ConnectionFactory() {
       try {
           Configuration cfg = new Configuration().configure().buildSessionFactory();
       } catch (Exception e) {
           // Do something useful
       }
   }

   public Session getSession() {
      Session session = null;
      try {
          session = sessionFactory.openSession();
      } catch (HibernateException e) {
          // Do Something useful
      }
      return session;
   }
Hibernate.cfg.xml
Alternative to hibernate.properties

Handles bigger applications better

Bind SessionFactory to JNDI Naming

Allows you to remove code like the following
and put it in a configuration file
 Configuration cfg = new Configuration().addClass(DVD.class);
Sample
                 hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC quot;-//Hibernate/Hibernate Configuration DTD//ENquot;
                         quot;http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtdquot;>
<hibernate-configuration>
    <!-- a SessionFactory instance listed as /jndi/name -->
    <session-factory name=quot;java:comp/env/hibernate/SessionFactoryquot;>
        <property name=quot;connection.datasourcequot;>java:/SomeDB</property>
        <property name=quot;show_sqlquot;>true</property>
        <property name=quot;dialectquot;>net.sf.hibernate.dialect.MySQLDialect</property>
        <property name=quot;use_outer_joinquot;>true</property>
        <property name=quot;transaction.factory_classquot;>net.sf.hibernate.transaction.JTATransactionFactory</>
        <property name=quot;jta.UserTransactionquot;>java:comp/UserTransaction</property>

      <!-- Mapping files -->
      <mapping resource=quot;com/shoesobjects/SomePOJO.hbm.xmlquot;/>
   </session-factory>
</hibernate-configuration>
Schema Generation


SchemaExport can generate or execute DDL
to generate the desired database schema

Can also update schema

Can be called via ant task
Code Generation


hbm2java

Parses hibernate mapping files and generates
POJO java classes on the fly.

Can be called via ant task
Mapping File Generation


 MapGenerator - part of Hibernate extensions

 Generates mapping file based on compiled
 classes. Some rules apply.

 Does repetitive grunt work
Links to live by

http://www.hibernate.org

http://www.springframework.org

http://www.jboss.org

http://raibledesigns.com/wiki/Wiki.jsp?
page=AppFuse

More Related Content

What's hot (20)

Spring boot
Spring bootSpring boot
Spring boot
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Servlets
ServletsServlets
Servlets
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Introduction to EJB
Introduction to EJBIntroduction to EJB
Introduction to EJB
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introduction
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 

Viewers also liked

Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To HibernateAmit Himani
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginnersRahul Jain
 
Hibernation PPT Lesson 9
Hibernation PPT Lesson 9Hibernation PPT Lesson 9
Hibernation PPT Lesson 9drlech123
 
Struts & hibernate ppt
Struts & hibernate pptStruts & hibernate ppt
Struts & hibernate pptPankaj Patel
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer ReferenceMuthuselvam RS
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewBrett Meyer
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesBrett Meyer
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionEr. Gaurav Kumar
 
JPA - Java Persistence API
JPA - Java Persistence APIJPA - Java Persistence API
JPA - Java Persistence APIThomas Wöhlke
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 

Viewers also liked (15)

Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
 
Hibernation PPT Lesson 9
Hibernation PPT Lesson 9Hibernation PPT Lesson 9
Hibernation PPT Lesson 9
 
Struts & hibernate ppt
Struts & hibernate pptStruts & hibernate ppt
Struts & hibernate ppt
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Torpor
TorporTorpor
Torpor
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic Introduction
 
JPA - Java Persistence API
JPA - Java Persistence APIJPA - Java Persistence API
JPA - Java Persistence API
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 

Similar to Hibernate ORM Object-Relational Mapping

hibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdfhibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdfMytrux1
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentationLuis Goldster
 
Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1PawanMM
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejugrobbiev
 
Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1Hitesh-Java
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Hugo Hamon
 
Hibernate - Part 2
Hibernate - Part 2 Hibernate - Part 2
Hibernate - Part 2 Hitesh-Java
 
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry PiGrâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry PiJérémy Derussé
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2PawanMM
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup PerformanceGreg Whalin
 
Introduction to Client Side Dev in SharePoint Workshop
Introduction to Client Side Dev in SharePoint WorkshopIntroduction to Client Side Dev in SharePoint Workshop
Introduction to Client Side Dev in SharePoint WorkshopMark Rackley
 
EJB et WS (Montreal JUG - 12 mai 2011)
EJB et WS (Montreal JUG - 12 mai 2011)EJB et WS (Montreal JUG - 12 mai 2011)
EJB et WS (Montreal JUG - 12 mai 2011)Montreal JUG
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate TutorialSyed Shahul
 
Symfony tips and tricks
Symfony tips and tricksSymfony tips and tricks
Symfony tips and tricksJavier Eguiluz
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingTricode (part of Dept)
 
OR Mapping- nhibernate Presentation
OR Mapping- nhibernate PresentationOR Mapping- nhibernate Presentation
OR Mapping- nhibernate PresentationShahzad
 

Similar to Hibernate ORM Object-Relational Mapping (20)

hibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdfhibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdf
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
 
5-Hibernate.ppt
5-Hibernate.ppt5-Hibernate.ppt
5-Hibernate.ppt
 
Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejug
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
 
Hibernate - Part 2
Hibernate - Part 2 Hibernate - Part 2
Hibernate - Part 2
 
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry PiGrâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup Performance
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup Performance
 
Introduction to Client Side Dev in SharePoint Workshop
Introduction to Client Side Dev in SharePoint WorkshopIntroduction to Client Side Dev in SharePoint Workshop
Introduction to Client Side Dev in SharePoint Workshop
 
EJB et WS (Montreal JUG - 12 mai 2011)
EJB et WS (Montreal JUG - 12 mai 2011)EJB et WS (Montreal JUG - 12 mai 2011)
EJB et WS (Montreal JUG - 12 mai 2011)
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Symfony tips and tricks
Symfony tips and tricksSymfony tips and tricks
Symfony tips and tricks
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
OR Mapping- nhibernate Presentation
OR Mapping- nhibernate PresentationOR Mapping- nhibernate Presentation
OR Mapping- nhibernate Presentation
 

Recently uploaded

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
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
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
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...
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 

Hibernate ORM Object-Relational Mapping

  • 1. Hibernate Object/Relational Mapping and Transparent Object Persistence for Java and SQL Databases
  • 2. Facts about Hibernate True transparent persistence Query language aligned with SQL Does not use byte code enhancement Free/open source
  • 3. What is Hibernate? ** Hibernate is a powerful, ultra-high performance object/relational persistence and query service for Java. Hibernate lets you develop persistent objects following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework. Extremely fine-grained, richly typed object models are possible. The Hibernate Query Language, designed as a quot;minimalquot; object-oriented extension to SQL, provides an elegant bridge between the object and relational worlds. Hibernate is now the most popular ORM solution for Java. ** http://www.hibernate.org
  • 4. Object-relational impedance mismatch Object databases are not the answer Application Objects cannot be easily persisted to relational databases Similar to the putting square peg into round hole
  • 5. Object/Relational Mapping (ORM) Mapping application objects to relational database Solution for infamous object-relational impedance mismatch Finally application can focus on objects
  • 6. Transparent Persistence Persist application objects without knowing what relational database is the target Persist application objects without “flattening” code weaved in and out of business logic
  • 7. Query Service Ability to retrieve sets of data based on criteria Aggregate operations like count, sum, min, max, etc.
  • 8. Why use Hibernate? Simple to get up and running Transparent Persistence achieved using Reflection Isn’t intrusive to the build/deploy process Persistence objects can follow common java idioms: Association, Inheritance, Polymorphism, Composition, Collections In most cases Java objects do not even know they can be persisted
  • 9. Why use Hibernate cont Java developer can focus on object modeling Feels much more natural than Entity Beans or JDBC coding Query mechanism closely resembles SQL so learning curve is low
  • 10. What makes up a Hibernate application? Standard domain objects defined in Java as POJO’s, nothing more. Hibernate mapping file Hibernate configuration file Hibernate Runtime Database
  • 11. What is missing from a Hibernate application? Flattening logic in Java code to conform to relational database design Inflation logic to resurrect Java object from persistent store Database specific tweaks
  • 12. Hibernate Classes SessionFactory - One instance per app. Creates Sessions. Consumer of hibernate configuration file. Session - Conversation between application and Hibernate Transaction Factory - Creates transactions to be used by application Transaction - Wraps transaction implementation(JTA, JDBC)
  • 13. Hibernate Sample App Standard Struts Web Application Deployed on JBoss Persisted to MySQL database All hand coded, didn’t use automated tools to generate Java classes, DDL, or mapping files Disclaimer: Made simple stupid on purpose
  • 14. DVD Library Functions Add DVD’s to your collection Output your collection
  • 15. Separation of Responsibility Persistence Struts JSP classes Action
  • 16. DVD POJO NOTE: public class DVD { I transform private Long id; the DVDForm Bean to DVD prior to persisting for private String name; added flexibility private String url; public Long getId() { return id; } public void setId(Long id) { this.id = id; } .. .. }
  • 17. Hibernate Mapping File DVD.hbm.xml <?xml version=quot;1.0quot;?> <!DOCTYPE hibernate-mapping PUBLIC quot;-//Hibernate/Hibernate Mapping DTD 2.0//ENquot; quot;http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtdquot;> <hibernate-mapping> <class name=quot;com.shoesobjects.DVDquot; table=quot;dvdlistquot;> <id name=quot;idquot; column=quot;idquot; type=quot;java.lang.Longquot; unsaved-value=quot;nullquot;> <generator class=quot;nativequot;/> </id> <property name=quot;namequot; column=quot;namequot; type=quot;java.lang.Stringquot; not-null=quot;truequot;/> <property name=quot;urlquot; column=quot;urlquot; type=quot;java.lang.Stringquot;/> </class> </hibernate-mapping>
  • 18. Hibernate.properties ################# ### Platforms ######## ################# ## JNDI Datasource hibernate.connection.datasource java:/DVDDB ## MySQL hibernate.dialect net.sf.hibernate.dialect.MySQLDialect hibernate.connection.driver_class org.gjt.mm.mysql.Driver hibernate.connection.driver_class com.mysql.jdbc.Driver
  • 19. DVDService Class public void updateDVD(DVD dvd) { Session session = ConnectionFactory.getInstance().getSession(); try { Transaction tx = session.beginTransaction(); session.update(dvd); tx.commit(); session.flush(); } catch (HibernateException e) { tx.rollback(); } finally { // Cleanup } }
  • 20. ConnectionFactory public class ConnectionFactory { private static ConnectionFactory instance = null; private SessionFactory sessionFactory = null; private ConnectionFactory() { try { Configuration cfg = new Configuration().addClass(DVD.class); sessionFactory = cfg.buildSessionFactory(); } catch (Exception e) { // Do something useful } } public Session getSession() { Session session = null; try { session = sessionFactory.openSession(); } catch (HibernateException e) { // Do Something useful } return session; }
  • 21. ConnectionFactory Improved public class ConnectionFactory { private static ConnectionFactory instance = null; private SessionFactory sessionFactory = null; private ConnectionFactory() { try { Configuration cfg = new Configuration().configure().buildSessionFactory(); } catch (Exception e) { // Do something useful } } public Session getSession() { Session session = null; try { session = sessionFactory.openSession(); } catch (HibernateException e) { // Do Something useful } return session; }
  • 22. Hibernate.cfg.xml Alternative to hibernate.properties Handles bigger applications better Bind SessionFactory to JNDI Naming Allows you to remove code like the following and put it in a configuration file Configuration cfg = new Configuration().addClass(DVD.class);
  • 23. Sample hibernate.cfg.xml <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC quot;-//Hibernate/Hibernate Configuration DTD//ENquot; quot;http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtdquot;> <hibernate-configuration> <!-- a SessionFactory instance listed as /jndi/name --> <session-factory name=quot;java:comp/env/hibernate/SessionFactoryquot;> <property name=quot;connection.datasourcequot;>java:/SomeDB</property> <property name=quot;show_sqlquot;>true</property> <property name=quot;dialectquot;>net.sf.hibernate.dialect.MySQLDialect</property> <property name=quot;use_outer_joinquot;>true</property> <property name=quot;transaction.factory_classquot;>net.sf.hibernate.transaction.JTATransactionFactory</> <property name=quot;jta.UserTransactionquot;>java:comp/UserTransaction</property> <!-- Mapping files --> <mapping resource=quot;com/shoesobjects/SomePOJO.hbm.xmlquot;/> </session-factory> </hibernate-configuration>
  • 24. Schema Generation SchemaExport can generate or execute DDL to generate the desired database schema Can also update schema Can be called via ant task
  • 25. Code Generation hbm2java Parses hibernate mapping files and generates POJO java classes on the fly. Can be called via ant task
  • 26. Mapping File Generation MapGenerator - part of Hibernate extensions Generates mapping file based on compiled classes. Some rules apply. Does repetitive grunt work
  • 27. Links to live by http://www.hibernate.org http://www.springframework.org http://www.jboss.org http://raibledesigns.com/wiki/Wiki.jsp? page=AppFuse