SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
Ram132
 

Was ist angesagt? (20)

Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Spring beans
Spring beansSpring beans
Spring beans
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Hibernate
HibernateHibernate
Hibernate
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 

Andere mochten auch

Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
hr1383
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
Brett Meyer
 

Andere mochten auch (14)

Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
 
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
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 

Ähnlich wie Hibernate Presentation

hibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdfhibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdf
Mytrux1
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejug
robbiev
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
Syed Shahul
 

Ähnlich wie Hibernate Presentation (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
 

Kürzlich hochgeladen

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 

Hibernate Presentation

  • 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