SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Downloaden Sie, um offline zu lesen
[          Hibernate in 60 Minutes           ]

                        Eric M. Burke
                      www.ericburke.com




April 14, 2005           Hibernate in 60 Minutes   1
[               My JDBC Experience                               ]
        Frustration drove me to investigate
         Hibernate
        Custom JDBC frameworks and idioms
             ○   Usually a class called JdbcUtil with static methods
          Custom code generators
             ○   Database metadata is too cool to resist
        Custom strategy for optimistic locking
        Database-specific ID generation

April 14, 2005                     Hibernate in 60 Minutes             2
[          Typical JDBC Problems                                      ]
        Massive duplication            Relationships are
        Tied to specific                really hard
         database                         ○   N+1 selects problem
                                          ○   parent/child updates
        Error-prone
                                                     delete all then add
         try/catch/finally
                                        Screen-specific
                                         DAOs for
                                         optimization


April 14, 2005          Hibernate in 60 Minutes                             3
[                Hibernate Questions                          ]
        How hard is it to learn and use?
        How invasive is it to my code?

        What are the configuration headaches?
             ○   Yet another framework with XML files, JAR files,
                 additional build complexity?
          Does it simplify my life?



April 14, 2005                   Hibernate in 60 Minutes            4
[                  What is Hibernate?                               ]
          Java Object/Relational Mapping
             ○   Open source – LGPL
             ○   http://www.hibernate.org/ (JBoss Group)
        Lets you avoid SQL
        Works with (almost) all relational DBs
             ○   DB2, FrontBase, HSQLDB, Informix, Ingres, Interbase,
                 Mckoi, MySQL, Oracle, Pointbase, PostgreSQL, Progress,
                 SAP DB, SQL Server, Sybase, etc...
             ○   Or you can extend one of the Dialect classes


April 14, 2005                      Hibernate in 60 Minutes               5
[          What is Hibernate? (Cont'd)                    ]
          Has a huge feature list
             ○   Go to their web site – we don't have time
          Maps JavaBeans (POJOs) to tables
             ○   XML defines the mappings
             ○   Very few bean requirements
          SQL is generated at app startup time
             ○   As opposed to bytecode manipulation
             ○   New database? No problem! Change a few props

April 14, 2005                    Hibernate in 60 Minutes       6
[                 Avoiding SQL                                  ]
          Hibernate Query Language approach
      public User getByScreenName(String screenName) {
        try {
          return (User) getSession().createQuery(
              "from User u where u.screenName=:screenName")
                  .setString("screenName", screenName)
                  .uniqueResult();
        } catch (HibernateException e) {
          throw new DaoException(e);              JavaBeans
        }                                         Property Name
      }

          Code-based query API
       public User getByScreenName(String screenName) {
         return getUnique(Expression.eq("screenName", screenName));
       }


April 14, 2005                 Hibernate in 60 Minutes                7
[          Sample Application Code                            ]
     Session session = getSessionFactory().openSession();

     // assume we know the root category id is 1
     Category rootCategory = (Category) session.load(
             Category.class, new Long(1));

     // we can immediately traverse the collection of messages
     // without any additional Hibernate code
     for (Object msgObj : rootCategory.getMessages()) {
         Message msg = (Message) msgObj; // generics+XDoclet==bad
         System.out.println(“Subject: “ + msg.getSubject());
         System.out.println(“Body: “ + msg.getBody());
         System.out.println();
     }

     session.close();



April 14, 2005                Hibernate in 60 Minutes               8
[     Sample Code with Transaction                            ]
      Session sess = ...
      Transaction tx = sess.beginTransaction();

      // find the root category using Criteria
      Criteria criteria = sess.createCriteria(Category.class);
      criteria.add(Expression.isNull("parentCategory"));
      Category rootCategory = (Category) criteria.uniqueResult();

      // change something
      rootCategory.setDescription(“The Root Category”);

      tx.commit();
      sess.close();




April 14, 2005                Hibernate in 60 Minutes               9
[               Development Options                  ]
          Start with the database
             ○   Use middlegen to generate mapping files
             ○   Use hbm2java to generate JavaBeans
          Start with JavaBeans C
             ○   Use XDoclet to generate mapping files
             ○   Use hbm2ddl to generate the database
          Start with the XML mapping files
             ○   Hand-code the mapping files
             ○   Use both hbm2java and hbm2ddl
April 14, 2005                   Hibernate in 60 Minutes   10
[                  Hibernate Tutorial                         ]
        Design the database
        Code some persistent classes

        Write an Ant buildfile
             ○   Generate the mapping files and hibernate.cfg.xml
        Choose a strategy for sessions and
         transactions (Spring framework)
        Write and test the DAOs

        Add business logic and helper methods

April 14, 2005                    Hibernate in 60 Minutes           11
[                        Database Design                                       ]
          Design your database first

                 Categories         Surrogate Keys                  Resources
                                      Work Best                   PK   id
        PK       id

                 name                                                  name
                                                                       url
                 description         many-to-one                       description
        FK1      parentCategoryId
                                                                       createdOn


                                         CategoriesResources
                                         PK,FK1     categoryId
                                         PK,FK2     resourceId
                                                                  many-to-many

April 14, 2005                          Hibernate in 60 Minutes                      12
[                     Persistent Objects                  ]
          POJOs - Plain Old Java Objects
             ○   No base class or interface requirement
        Must have public no-arg constructor
        Should have getter/setters
             ○   Or Hibernate can access fields directly
             ○   Hibernate uses JavaBeans property names
                     For mappings as well as in queries
        Serializable is recommended
        XDoclet tags are useful but not required
April 14, 2005                        Hibernate in 60 Minutes   13
[                     My Base Class                                     ]
           public class PersistentClass implements Serializable {
               private static final long serialVersionUID = 1;
               private Long id;

                 /**
                  * @hibernate.id
                  *      column="id"
                  *      unsaved-value="null"
                  *      generator-class="native"
                  *      access="field"
                  */
                 public Long getId() {           Hibernate   assigns the id
                     return id;
                 }

                 private void setId(Long id) {
                     this.id = id;
                 }
           }


April 14, 2005                     Hibernate in 60 Minutes                    14
[                      Category Class                                   ]
         public class Category extends NameDescription {
             private static final long serialVersionUID = 1;
                                                                       My base
                 private Set childCategories = new HashSet();
                 private Set resources = new HashSet();
                                                                       class, not
                 private Category parentCategory;                     Hibernate's
                 public Category() {
                 }

                 public Category(String name, String description) {
                     super(name, description);
                 }

                 public Set getChildCategories() {
                     return childCategories;
                 }

                 public void setChildCategories(Set childCategories) {
                     this.childCategories = childCategories;
                 }
April 14, 2005                         Hibernate in 60 Minutes                  15
[                   Category (Cont'd)                                 ]
                 public Category getParentCategory() {
                     return parentCategory;
                 }

                 public void setParentCategory(Category parentCategory) {
                     this.parentCategory = parentCategory;
                 }

                 public Set getResources() {
                     return resources;
                 }

                 public void setResources(Set resources) {
                     this.resources = resources;
                 }
          }




April 14, 2005                     Hibernate in 60 Minutes                  16
[                 Mapping Files
                                                         Or Java 5
                                                         Annotations    ]
          Generated by XDoclet, 1 per persistent bean
 <hibernate-mapping>
   <class name="com.ericburke.linkblog.model.Category"
       table="Categories">
     <id name="id" column="id" type="java.lang.Long"
         unsaved-value="null">
       <generator class="native"/>
     </id>

       <set name="childCategories" lazy="true"
            inverse="true" cascade="save-update">
         <key column="parentCategoryId"/>
         <one-to-many class="com.ericburke.linkblog.model.Category"/>
       </set>

       <many-to-one name="parentCategory"
           class="com.ericburke.linkblog.model.Category"
           cascade="none" column="parentCategoryId" not-null="false"/>


April 14, 2005                 Hibernate in 60 Minutes                   17
[           Mapping Files (Cont'd)                           ]
          <set name="resources" table="CategoriesResources"
               lazy="true" cascade="save-update">
            <key column="categoryId"/>
            <many-to-many column=”resourceId”
                 class="com.ericburke.linkblog.model.Resource"/>
          </set>

          <property name="name" type="java.lang.String"
                    column="name" length="255"/>

       <property name="description" type="java.lang.String"
                 column="description" length="2000"/>
     </class>
   </hibernate-mapping>




April 14, 2005                   Hibernate in 60 Minutes           18
[             Xdoclet Tag Example                               ]
      /**
       * @hibernate.class table="Categories"
       */
      public class Category extends NameDescription {

            /**
              * @hibernate.set cascade="save-update" inverse="true"
              *     lazy="true"
              * @hibernate.collection-key column="parentCategoryId"
              * @hibernate.collection-one-to-many
              *     class="com.ericburke.linkblog.model.Category"
              */
            public Set getChildCategories() {
                 return childCategories;
            }

            // no tags on the setters
            public void setChildCategories(Set childCategories) { }


April 14, 2005                   Hibernate in 60 Minutes              19
[             hibernate.cfg.xml                                       ]
                                                 Generated by XDoclet, or
  <hibernate-configuration>                      use Spring's XML file
    <session-factory>
      <property name="dialect">
         net.sf.hibernate.dialect.HSQLDialect</property>
      <property name="show_sql">true</property>
      <property name="use_outer_join">false</property>
      <property name="connection.username">sa</property>
      <property name="connection.driver_class">
         org.hsqldb.jdbcDriver</property>
      <property name="connection.url">
         jdbc:hsqldb:hsql://localhost/linkblog</property>
      <property name="connection.pool_size">5</property>

      <mapping
          resource="com/ericburke/linkblog/model/Category.hbm.xml"/>
      <mapping
          resource="com/ericburke/linkblog/model/Resource.hbm.xml"/>
    </session-factory>
  </hibernate-configuration>

April 14, 2005               Hibernate in 60 Minutes                        20
[                      Ant Buildfile                                    ]
          Invokes XDoclet
             ○   XDoclet ships with the Hibernate tasks
             ○   Generates mapping files and hibernate.cfg.xml
          Hibernate includes tasks for
             ○   hbm2java – generates the persistent classes
             ○   hbm2ddl – generates the database           Requires the persistent
                                                              .class files in the
                                                             taskdef's classpath
          Classpath needs
             ○   Hibernate Jars, Hibernate extensions, XDoclet,
                 JDBC driver JAR file
April 14, 2005                    Hibernate in 60 Minutes                       21
[                       HibernateUtil                           ]
          Trivial examples show this class
             ○   Creates a SessionFactory in the static initializer
                 Configuration cfg = new Configuration();
                 SessionFactory sessionFactory =
                     cfg.configure("/hibernate.cfg.xml")
                        .buildSessionFactory();
          Provides access to a Session ThreadLocal
           public static Session getSession() {
               Session s = (Session) threadSession.get();
               if (s == null) {
                   s = sessionFactory.openSession();
                   threadSession.set(s);
               }
               return s;
          APIs to begin/commit/rollback transactions
April 14, 2005                     Hibernate in 60 Minutes            22
[                                DAOs                     ]
        Insulate your code from Hibernate specifics
        CRUD operations
             ○   I use Java 5 generics heavily
             ○   You can also use Spring for DAO support
          Locating persistent objects
             ○   Use Hibernate queries for efficiency
             ○   From there, walk the graph using normal Java
                 collections semantics
                     Detached objects can be challenging

April 14, 2005                        Hibernate in 60 Minutes   23
[                     Servlet Filter                                  ]
    public class HibernateFilter implements Filter {
        public void init(FilterConfig fc) throws ServletException {
        }

            public void destroy() {
            }

            public void doFilter(ServletRequest req, ServletResponse res,
                                 FilterChain filterChain)
                    throws IOException, ServletException {
                try {
                    filterChain.doFilter(req, res);
                    HibernateUtil.commitTransaction();
                } finally {                                Hibernate in Action,
                    HibernateUtil.closeSession();               page 304
                }
            }
    }



April 14, 2005                      Hibernate in 60 Minutes                       24
[                    Business Objects                             ]
          A layer between your application code and
           the DAOs
             ○   Only allow business objects to hit the DAOs
             ○   Business objects and app code use persistent objects
          Provide a consistent place to use AOP
             ○   try/catch/finally for transactions
          Risk duplicating DAO code
             ○   Sometimes business object methods just delegate

April 14, 2005                     Hibernate in 60 Minutes              25
[            Architecture Summary                                       ]
      AOP for
    Transactions

                   Business
                                    DAOs                Hibernate       Database
                   Objects


     Application
       Code                          Persistent               XML
                                      Objects                Mappings

             Keep an
           Open Session

April 14, 2005                Hibernate in 60 Minutes                              26
[                            Gotchas                      ]
          Must always have an open session
             ○   Seemingly innocent code like fetching a lazy
                 collection bombs
             ○   Swing – open a session on event thread
             ○   Servlets – use a filter or Spring
          Hibernate tasks do not abort Ant
             ○   No failonerror attribute
             ○   Watch the build output carefully
          Test associations and collections heavily
April 14, 2005                     Hibernate in 60 Minutes      27
[          When Not to Use Hibernate                  ]
          A horrible database design is forced on you
             ○   Many composite keys
          If your application is mostly mass
           operations
             ○   See pg. 181 “Hibernate in Action”
             ○   You might exhaust available heap space
          ??


April 14, 2005                    Hibernate in 60 Minutes   28
[      10 Reasons to Love Hibernate                ]
       1.Dynamic UPDATE          6.No more DTOs
         generation – figure out 7.Query result paging
         which columns
         changed                 8.Automatic dirty
                                   checking
       2.Trying new databases
                                 9.Good price
       3.Traversing
         associations            10.Good documentation
       4.Optimistic Locking
       5.ID generation
April 14, 2005           Hibernate in 60 Minutes         29

Weitere ähnliche Inhalte

Was ist angesagt?

Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingAnton Keks
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Agora Group
 
JavaFX and Scala in the Cloud: Stephen Chin
JavaFX and Scala in the Cloud: Stephen ChinJavaFX and Scala in the Cloud: Stephen Chin
JavaFX and Scala in the Cloud: Stephen Chinjaxconf
 
Kerberizing spark. Spark Summit east
Kerberizing spark. Spark Summit eastKerberizing spark. Spark Summit east
Kerberizing spark. Spark Summit eastJorge Lopez-Malla
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsAnton Keks
 
Cassandra EU 2012 - CQL: Then, Now and When by Eric Evans
Cassandra EU 2012 - CQL: Then, Now and When by Eric Evans Cassandra EU 2012 - CQL: Then, Now and When by Eric Evans
Cassandra EU 2012 - CQL: Then, Now and When by Eric Evans Acunu
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIAnton Keks
 
Java Beans Unit 4(part 2)
Java Beans Unit 4(part 2)Java Beans Unit 4(part 2)
Java Beans Unit 4(part 2)SURBHI SAROHA
 
Deployment in Oracle SOA Suite and in Oracle BPM Suite
Deployment in Oracle SOA Suite and in Oracle BPM SuiteDeployment in Oracle SOA Suite and in Oracle BPM Suite
Deployment in Oracle SOA Suite and in Oracle BPM SuiteLonneke Dikmans
 
IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...
IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...
IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...npinto
 
02 hibernateintroduction
02 hibernateintroduction02 hibernateintroduction
02 hibernateintroductionthirumuru2012
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: IntroductionAnton Keks
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: BasicsAnton Keks
 
Sdtl manual
Sdtl manualSdtl manual
Sdtl manualqaz8989
 
An Overview of ModeShape
An Overview of ModeShapeAn Overview of ModeShape
An Overview of ModeShapeRandall Hauch
 
Java Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & EncodingsJava Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & EncodingsAnton Keks
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateAnton Keks
 

Was ist angesagt? (20)

Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
 
Oo python
Oo pythonOo python
Oo python
 
1_JavIntro
1_JavIntro1_JavIntro
1_JavIntro
 
JavaFX and Scala in the Cloud: Stephen Chin
JavaFX and Scala in the Cloud: Stephen ChinJavaFX and Scala in the Cloud: Stephen Chin
JavaFX and Scala in the Cloud: Stephen Chin
 
Kerberizing spark. Spark Summit east
Kerberizing spark. Spark Summit eastKerberizing spark. Spark Summit east
Kerberizing spark. Spark Summit east
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
 
Cassandra EU 2012 - CQL: Then, Now and When by Eric Evans
Cassandra EU 2012 - CQL: Then, Now and When by Eric Evans Cassandra EU 2012 - CQL: Then, Now and When by Eric Evans
Cassandra EU 2012 - CQL: Then, Now and When by Eric Evans
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
 
Java Beans Unit 4(part 2)
Java Beans Unit 4(part 2)Java Beans Unit 4(part 2)
Java Beans Unit 4(part 2)
 
Deployment in Oracle SOA Suite and in Oracle BPM Suite
Deployment in Oracle SOA Suite and in Oracle BPM SuiteDeployment in Oracle SOA Suite and in Oracle BPM Suite
Deployment in Oracle SOA Suite and in Oracle BPM Suite
 
IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...
IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...
IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...
 
02 hibernateintroduction
02 hibernateintroduction02 hibernateintroduction
02 hibernateintroduction
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: Introduction
 
Drools presentation
Drools presentationDrools presentation
Drools presentation
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
 
Sdtl manual
Sdtl manualSdtl manual
Sdtl manual
 
An Overview of ModeShape
An Overview of ModeShapeAn Overview of ModeShape
An Overview of ModeShape
 
Java Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & EncodingsJava Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & Encodings
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, Hibernate
 

Andere mochten auch

Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesecosio GmbH
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentationJohn Slick
 
JPA - Java Persistence API
JPA - Java Persistence APIJPA - Java Persistence API
JPA - Java Persistence APIThomas Wöhlke
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginnersRahul Jain
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewCraig Dickson
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To HibernateAmit Himani
 
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 StepGuo Albert
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewBrett Meyer
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 

Andere mochten auch (12)

Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
JPA - Java Persistence API
JPA - Java Persistence APIJPA - Java Persistence API
JPA - Java Persistence API
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
 
Hibernate 3
Hibernate 3Hibernate 3
Hibernate 3
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief Overview
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
 
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
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
JPA Best Practices
JPA Best PracticesJPA Best Practices
JPA Best Practices
 

Ähnlich wie hibernate

XPages and Java (DanNotes 50th conference, November 2013)
XPages and Java (DanNotes 50th conference, November 2013)XPages and Java (DanNotes 50th conference, November 2013)
XPages and Java (DanNotes 50th conference, November 2013)Per Henrik Lausten
 
Writing Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason LeeWriting Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason Leejaxconf
 
How to train the jdt dragon
How to train the jdt dragonHow to train the jdt dragon
How to train the jdt dragonAyushman Jain
 
GOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesGOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesAlexandra Masterson
 
Hibernate
HibernateHibernate
HibernateAjay K
 
Hibernate for Beginners
Hibernate for BeginnersHibernate for Beginners
Hibernate for BeginnersRamesh Kumar
 
Easy Data Object Relational Mapping Tool
Easy Data Object Relational Mapping ToolEasy Data Object Relational Mapping Tool
Easy Data Object Relational Mapping ToolHasitha Guruge
 
SeaJUG May 2012 mybatis
SeaJUG May 2012 mybatisSeaJUG May 2012 mybatis
SeaJUG May 2012 mybatisWill Iverson
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate TutorialSyed Shahul
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
hibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdfhibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdfMytrux1
 
Create custom looping procedures in sql server 2005 tech republic
Create custom looping procedures in sql server 2005   tech republicCreate custom looping procedures in sql server 2005   tech republic
Create custom looping procedures in sql server 2005 tech republicKaing Menglieng
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7Deniz Oguz
 
Content Storage With Apache Jackrabbit
Content Storage With Apache JackrabbitContent Storage With Apache Jackrabbit
Content Storage With Apache JackrabbitJukka Zitting
 
Java Unit Testing with Unitils
Java Unit Testing with UnitilsJava Unit Testing with Unitils
Java Unit Testing with UnitilsMikalai Alimenkou
 

Ähnlich wie hibernate (20)

Hibernate
HibernateHibernate
Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
XPages and Java (DanNotes 50th conference, November 2013)
XPages and Java (DanNotes 50th conference, November 2013)XPages and Java (DanNotes 50th conference, November 2013)
XPages and Java (DanNotes 50th conference, November 2013)
 
Writing Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason LeeWriting Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason Lee
 
Introduction to jOOQ
Introduction to jOOQIntroduction to jOOQ
Introduction to jOOQ
 
How to train the jdt dragon
How to train the jdt dragonHow to train the jdt dragon
How to train the jdt dragon
 
GOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesGOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter Slides
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate for Beginners
Hibernate for BeginnersHibernate for Beginners
Hibernate for Beginners
 
Easy Data Object Relational Mapping Tool
Easy Data Object Relational Mapping ToolEasy Data Object Relational Mapping Tool
Easy Data Object Relational Mapping Tool
 
SeaJUG May 2012 mybatis
SeaJUG May 2012 mybatisSeaJUG May 2012 mybatis
SeaJUG May 2012 mybatis
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
hibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdfhibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdf
 
Create custom looping procedures in sql server 2005 tech republic
Create custom looping procedures in sql server 2005   tech republicCreate custom looping procedures in sql server 2005   tech republic
Create custom looping procedures in sql server 2005 tech republic
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Java >= 9
Java >= 9Java >= 9
Java >= 9
 
Content Storage With Apache Jackrabbit
Content Storage With Apache JackrabbitContent Storage With Apache Jackrabbit
Content Storage With Apache Jackrabbit
 
Java Unit Testing with Unitils
Java Unit Testing with UnitilsJava Unit Testing with Unitils
Java Unit Testing with Unitils
 
55j7
55j755j7
55j7
 

Mehr von Arjun Shanka (20)

Asp.net w3schools
Asp.net w3schoolsAsp.net w3schools
Asp.net w3schools
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Sms several papers
Sms several papersSms several papers
Sms several papers
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
System simulation 06_cs82
System simulation 06_cs82System simulation 06_cs82
System simulation 06_cs82
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
javainheritance
javainheritancejavainheritance
javainheritance
 
javarmi
javarmijavarmi
javarmi
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
javapackage
javapackagejavapackage
javapackage
 
javaarray
javaarrayjavaarray
javaarray
 
swingbasics
swingbasicsswingbasics
swingbasics
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
struts
strutsstruts
struts
 
javathreads
javathreadsjavathreads
javathreads
 
javabeans
javabeansjavabeans
javabeans
 
72185-26528-StrutsMVC
72185-26528-StrutsMVC72185-26528-StrutsMVC
72185-26528-StrutsMVC
 
javanetworking
javanetworkingjavanetworking
javanetworking
 
javaiostream
javaiostreamjavaiostream
javaiostream
 
servlets
servletsservlets
servlets
 

Kürzlich hochgeladen

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
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 TerraformAndrey Devyatkin
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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
 

Kürzlich hochgeladen (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 

hibernate

  • 1. [ Hibernate in 60 Minutes ] Eric M. Burke www.ericburke.com April 14, 2005 Hibernate in 60 Minutes 1
  • 2. [ My JDBC Experience ]  Frustration drove me to investigate Hibernate  Custom JDBC frameworks and idioms ○ Usually a class called JdbcUtil with static methods  Custom code generators ○ Database metadata is too cool to resist  Custom strategy for optimistic locking  Database-specific ID generation April 14, 2005 Hibernate in 60 Minutes 2
  • 3. [ Typical JDBC Problems ]  Massive duplication  Relationships are  Tied to specific really hard database ○ N+1 selects problem ○ parent/child updates  Error-prone  delete all then add try/catch/finally  Screen-specific DAOs for optimization April 14, 2005 Hibernate in 60 Minutes 3
  • 4. [ Hibernate Questions ]  How hard is it to learn and use?  How invasive is it to my code?  What are the configuration headaches? ○ Yet another framework with XML files, JAR files, additional build complexity?  Does it simplify my life? April 14, 2005 Hibernate in 60 Minutes 4
  • 5. [ What is Hibernate? ]  Java Object/Relational Mapping ○ Open source – LGPL ○ http://www.hibernate.org/ (JBoss Group)  Lets you avoid SQL  Works with (almost) all relational DBs ○ DB2, FrontBase, HSQLDB, Informix, Ingres, Interbase, Mckoi, MySQL, Oracle, Pointbase, PostgreSQL, Progress, SAP DB, SQL Server, Sybase, etc... ○ Or you can extend one of the Dialect classes April 14, 2005 Hibernate in 60 Minutes 5
  • 6. [ What is Hibernate? (Cont'd) ]  Has a huge feature list ○ Go to their web site – we don't have time  Maps JavaBeans (POJOs) to tables ○ XML defines the mappings ○ Very few bean requirements  SQL is generated at app startup time ○ As opposed to bytecode manipulation ○ New database? No problem! Change a few props April 14, 2005 Hibernate in 60 Minutes 6
  • 7. [ Avoiding SQL ]  Hibernate Query Language approach public User getByScreenName(String screenName) { try { return (User) getSession().createQuery( "from User u where u.screenName=:screenName") .setString("screenName", screenName) .uniqueResult(); } catch (HibernateException e) { throw new DaoException(e); JavaBeans } Property Name }  Code-based query API public User getByScreenName(String screenName) { return getUnique(Expression.eq("screenName", screenName)); } April 14, 2005 Hibernate in 60 Minutes 7
  • 8. [ Sample Application Code ] Session session = getSessionFactory().openSession(); // assume we know the root category id is 1 Category rootCategory = (Category) session.load( Category.class, new Long(1)); // we can immediately traverse the collection of messages // without any additional Hibernate code for (Object msgObj : rootCategory.getMessages()) { Message msg = (Message) msgObj; // generics+XDoclet==bad System.out.println(“Subject: “ + msg.getSubject()); System.out.println(“Body: “ + msg.getBody()); System.out.println(); } session.close(); April 14, 2005 Hibernate in 60 Minutes 8
  • 9. [ Sample Code with Transaction ] Session sess = ... Transaction tx = sess.beginTransaction(); // find the root category using Criteria Criteria criteria = sess.createCriteria(Category.class); criteria.add(Expression.isNull("parentCategory")); Category rootCategory = (Category) criteria.uniqueResult(); // change something rootCategory.setDescription(“The Root Category”); tx.commit(); sess.close(); April 14, 2005 Hibernate in 60 Minutes 9
  • 10. [ Development Options ]  Start with the database ○ Use middlegen to generate mapping files ○ Use hbm2java to generate JavaBeans  Start with JavaBeans C ○ Use XDoclet to generate mapping files ○ Use hbm2ddl to generate the database  Start with the XML mapping files ○ Hand-code the mapping files ○ Use both hbm2java and hbm2ddl April 14, 2005 Hibernate in 60 Minutes 10
  • 11. [ Hibernate Tutorial ]  Design the database  Code some persistent classes  Write an Ant buildfile ○ Generate the mapping files and hibernate.cfg.xml  Choose a strategy for sessions and transactions (Spring framework)  Write and test the DAOs  Add business logic and helper methods April 14, 2005 Hibernate in 60 Minutes 11
  • 12. [ Database Design ]  Design your database first Categories Surrogate Keys Resources Work Best PK id PK id name name url description many-to-one description FK1 parentCategoryId createdOn CategoriesResources PK,FK1 categoryId PK,FK2 resourceId many-to-many April 14, 2005 Hibernate in 60 Minutes 12
  • 13. [ Persistent Objects ]  POJOs - Plain Old Java Objects ○ No base class or interface requirement  Must have public no-arg constructor  Should have getter/setters ○ Or Hibernate can access fields directly ○ Hibernate uses JavaBeans property names  For mappings as well as in queries  Serializable is recommended  XDoclet tags are useful but not required April 14, 2005 Hibernate in 60 Minutes 13
  • 14. [ My Base Class ] public class PersistentClass implements Serializable { private static final long serialVersionUID = 1; private Long id; /** * @hibernate.id * column="id" * unsaved-value="null" * generator-class="native" * access="field" */ public Long getId() { Hibernate assigns the id return id; } private void setId(Long id) { this.id = id; } } April 14, 2005 Hibernate in 60 Minutes 14
  • 15. [ Category Class ] public class Category extends NameDescription { private static final long serialVersionUID = 1; My base private Set childCategories = new HashSet(); private Set resources = new HashSet(); class, not private Category parentCategory; Hibernate's public Category() { } public Category(String name, String description) { super(name, description); } public Set getChildCategories() { return childCategories; } public void setChildCategories(Set childCategories) { this.childCategories = childCategories; } April 14, 2005 Hibernate in 60 Minutes 15
  • 16. [ Category (Cont'd) ] public Category getParentCategory() { return parentCategory; } public void setParentCategory(Category parentCategory) { this.parentCategory = parentCategory; } public Set getResources() { return resources; } public void setResources(Set resources) { this.resources = resources; } } April 14, 2005 Hibernate in 60 Minutes 16
  • 17. [ Mapping Files Or Java 5 Annotations ]  Generated by XDoclet, 1 per persistent bean <hibernate-mapping> <class name="com.ericburke.linkblog.model.Category" table="Categories"> <id name="id" column="id" type="java.lang.Long" unsaved-value="null"> <generator class="native"/> </id> <set name="childCategories" lazy="true" inverse="true" cascade="save-update"> <key column="parentCategoryId"/> <one-to-many class="com.ericburke.linkblog.model.Category"/> </set> <many-to-one name="parentCategory" class="com.ericburke.linkblog.model.Category" cascade="none" column="parentCategoryId" not-null="false"/> April 14, 2005 Hibernate in 60 Minutes 17
  • 18. [ Mapping Files (Cont'd) ] <set name="resources" table="CategoriesResources" lazy="true" cascade="save-update"> <key column="categoryId"/> <many-to-many column=”resourceId” class="com.ericburke.linkblog.model.Resource"/> </set> <property name="name" type="java.lang.String" column="name" length="255"/> <property name="description" type="java.lang.String" column="description" length="2000"/> </class> </hibernate-mapping> April 14, 2005 Hibernate in 60 Minutes 18
  • 19. [ Xdoclet Tag Example ] /** * @hibernate.class table="Categories" */ public class Category extends NameDescription { /** * @hibernate.set cascade="save-update" inverse="true" * lazy="true" * @hibernate.collection-key column="parentCategoryId" * @hibernate.collection-one-to-many * class="com.ericburke.linkblog.model.Category" */ public Set getChildCategories() { return childCategories; } // no tags on the setters public void setChildCategories(Set childCategories) { } April 14, 2005 Hibernate in 60 Minutes 19
  • 20. [ hibernate.cfg.xml ] Generated by XDoclet, or <hibernate-configuration> use Spring's XML file <session-factory> <property name="dialect"> net.sf.hibernate.dialect.HSQLDialect</property> <property name="show_sql">true</property> <property name="use_outer_join">false</property> <property name="connection.username">sa</property> <property name="connection.driver_class"> org.hsqldb.jdbcDriver</property> <property name="connection.url"> jdbc:hsqldb:hsql://localhost/linkblog</property> <property name="connection.pool_size">5</property> <mapping resource="com/ericburke/linkblog/model/Category.hbm.xml"/> <mapping resource="com/ericburke/linkblog/model/Resource.hbm.xml"/> </session-factory> </hibernate-configuration> April 14, 2005 Hibernate in 60 Minutes 20
  • 21. [ Ant Buildfile ]  Invokes XDoclet ○ XDoclet ships with the Hibernate tasks ○ Generates mapping files and hibernate.cfg.xml  Hibernate includes tasks for ○ hbm2java – generates the persistent classes ○ hbm2ddl – generates the database Requires the persistent .class files in the taskdef's classpath  Classpath needs ○ Hibernate Jars, Hibernate extensions, XDoclet, JDBC driver JAR file April 14, 2005 Hibernate in 60 Minutes 21
  • 22. [ HibernateUtil ]  Trivial examples show this class ○ Creates a SessionFactory in the static initializer Configuration cfg = new Configuration(); SessionFactory sessionFactory = cfg.configure("/hibernate.cfg.xml") .buildSessionFactory();  Provides access to a Session ThreadLocal public static Session getSession() { Session s = (Session) threadSession.get(); if (s == null) { s = sessionFactory.openSession(); threadSession.set(s); } return s;  APIs to begin/commit/rollback transactions April 14, 2005 Hibernate in 60 Minutes 22
  • 23. [ DAOs ]  Insulate your code from Hibernate specifics  CRUD operations ○ I use Java 5 generics heavily ○ You can also use Spring for DAO support  Locating persistent objects ○ Use Hibernate queries for efficiency ○ From there, walk the graph using normal Java collections semantics  Detached objects can be challenging April 14, 2005 Hibernate in 60 Minutes 23
  • 24. [ Servlet Filter ] public class HibernateFilter implements Filter { public void init(FilterConfig fc) throws ServletException { } public void destroy() { } public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException { try { filterChain.doFilter(req, res); HibernateUtil.commitTransaction(); } finally { Hibernate in Action, HibernateUtil.closeSession(); page 304 } } } April 14, 2005 Hibernate in 60 Minutes 24
  • 25. [ Business Objects ]  A layer between your application code and the DAOs ○ Only allow business objects to hit the DAOs ○ Business objects and app code use persistent objects  Provide a consistent place to use AOP ○ try/catch/finally for transactions  Risk duplicating DAO code ○ Sometimes business object methods just delegate April 14, 2005 Hibernate in 60 Minutes 25
  • 26. [ Architecture Summary ] AOP for Transactions Business DAOs Hibernate Database Objects Application Code Persistent XML Objects Mappings Keep an Open Session April 14, 2005 Hibernate in 60 Minutes 26
  • 27. [ Gotchas ]  Must always have an open session ○ Seemingly innocent code like fetching a lazy collection bombs ○ Swing – open a session on event thread ○ Servlets – use a filter or Spring  Hibernate tasks do not abort Ant ○ No failonerror attribute ○ Watch the build output carefully  Test associations and collections heavily April 14, 2005 Hibernate in 60 Minutes 27
  • 28. [ When Not to Use Hibernate ]  A horrible database design is forced on you ○ Many composite keys  If your application is mostly mass operations ○ See pg. 181 “Hibernate in Action” ○ You might exhaust available heap space  ?? April 14, 2005 Hibernate in 60 Minutes 28
  • 29. [ 10 Reasons to Love Hibernate ] 1.Dynamic UPDATE 6.No more DTOs generation – figure out 7.Query result paging which columns changed 8.Automatic dirty checking 2.Trying new databases 9.Good price 3.Traversing associations 10.Good documentation 4.Optimistic Locking 5.ID generation April 14, 2005 Hibernate in 60 Minutes 29