SlideShare a Scribd company logo
1 of 37
Professional Open Source™




           Hibernate Introduction
            Hello World and the Hibernate APIs




© JBoss, Inc. 2003, 2004.                                         07/17/04   1
Hello World I
                                                                      Professional Open Source™


  The Hello World program prints messages
           – To demonstrate Hibernate, let’s define a persistent message
           – we use a Message persistent class, POJO style


                            package hello;

                            public class Message {
                                private Long id;
                                private String text;

                                public String getText() {
                                    return text;
                                }

                                public void setText(String text) {
                                    this.text = text;
                                }

                                …
                            }



© JBoss, Inc. 2003, 2004.                                                                         2
Hello World II
                                                                        Professional Open Source™


  Messages don't have to be persistent!
           – we can use our persistent classes “outside” of Hibernate
           – Hibernate is able to “manage” persistent instances
           – but POJO persistent classes don't depend on Hibernate




                            Message message = new Message("Hello World");
                            System.out.println( message.getText() );




© JBoss, Inc. 2003, 2004.                                                                           3
Hello World VI
                                                                Professional Open Source™


  XML mapping metadata:


         <?xml version="1.0"?>
         <!DOCTYPE hibernate-mapping PUBLIC
             "-//Hibernate/Hibernate Mapping DTD//EN"
             "http://hibernate.sf.net/hibernate-mapping-2.0.dtd">

         <hibernate-mapping>

                   <class
                       name="hello.Message"
                       table="MESSAGES">

                            <id>...</id>

                            <property
                                name="text"
                                column="MESSAGE_TEXT"/>

                   </class>

         </hibernate-mapping>


© JBoss, Inc. 2003, 2004.                                                                   4
Using C3P0 with hibernate.properties
                                                                   Professional Open Source™


  Let's configure Hibernate to use C3P0 connection pooling
           Hibernate automatically loads hibernate.properties from a root
              directory of the classpath


          hibernate.connection.driver_class = com.mysql.jdbc.Driver
          hibernate.connection.url = jdbc:mysql://localhost/helloworld
          hibernate.connection.username = root
          hibernate.connection.password = root

          hibernate.dialect = org.hibernate.dialect.mySQLDialect

          hibernate.c3p0.min_size = 5
          hibernate.c3p0.max_size = 20
          hibernate.c3p0.timeout = 1800
          hibernate.c3p0.max_statements = 50
          Hibernate.c3p0.validate = true


                            Don't forget to set the SQL dialect!



© JBoss, Inc. 2003, 2004.                                                                      5
Starting Hibernate
                                                                       Professional Open Source™


  We create a SessionFactory using a Configuration
           –     download and install JDBC driver in classpath
           –     copy Hibernate and the required 3rd party libraries
           –     chose a JDBC connection pool, customize properties
           –     add mapping files to the Configuration
           –     build the SessionFactory (immutable!)




         SessionFactory sessionFactory = new Configuration()
             .addResource("hello/Message.hbm.xml")
             .buildSessionFactory();




© JBoss, Inc. 2003, 2004.                                                                          6
Configuring hibernate.cfg.xml
                                                                                      Professional Open Source™


  Let's configure Hibernate using hibernate.cfg.xml


         <hibernate-configuration>
         <!-- a SessionFactory instance listed as /jndi/name -->
              <session-factory>
                  <!-- properties -->
                 <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
                 <property name="show_sql">true</property>
                 <property name="use_outer_join">false</property>
                 <property name="connection.username">root</property>
                 <property name="connection.password">root</property>
                 <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
                 <property name="connection.url">jdbc:mysql://localhost/helloworld</property>
                 <property name="hibernate.hbm2ddl.auto">insert</property>
               <!-- mapping files -->
                <property name="cache.provider_class"> org.hibernate.cache.NoCacheProvider</property>
                <!-- mapping files -->
                                   <mapping resource="hello/Message.hbm.xml"/>
               </session-factory>

         </hibernate-configuration>




© JBoss, Inc. 2003, 2004.                                                                                         7
Starting Hibernate
                                                                       Professional Open Source™


  We create a SessionFactory using a Configuration
           –     download and install JDBC driver in classpath
           –     copy Hibernate and the required 3rd party libraries
           –     chose a JDBC connection pool, customize properties
           –     add mapping files to the Configuration
           –     build the SessionFactory (immutable!)




         SessionFactory sessionFactory = new Configuration()
                                       .configure().buildSessionFactory();




© JBoss, Inc. 2003, 2004.                                                                          8
Configuring Logging SQL
                                                           Professional Open Source™


  You have to configure the following hibernate.cfg.xml

  <property name="show_sql">true</property>
  <property name="format_sql">true</property>




© JBoss, Inc. 2003, 2004.                                                              9
Hello World III
                                                               Professional Open Source™


  Let's persist a message with Session and Transaction:


             Session session = getSessionFactory().openSession();
             Transaction tx = session.beginTransaction();

             Message message = new Message("Hello World");
             session.save(message);

             tx.commit();
             session.close();



  Hibernate executes this SQL:



             insert into MESSAGES (MESSAGE_ID, MESSAGE_TEXT)
                           values (1, 'Hello World')



© JBoss, Inc. 2003, 2004.                                                                  10
Hello World IV
                                                               Professional Open Source™


  Let's show all persistent messages:

         Session newSession = getSessionFactory().openSession();
         Transaction newTransaction = newSession.beginTransaction();
         Query query== newSession.createQuery("from Message");

         List messages =query.list();

         System.out.println( messages.size() + " message(s) found:" );

         for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
             Message message = (Message) iter.next();
             System.out.println( message.getText() );
         }

         newTransaction.commit();
         newSession.close();



             select m.MESSAGE_ID, m.MESSAGE_TEXT from MESSAGES m


© JBoss, Inc. 2003, 2004.                                                                  11
Hello World V
                                                                    Professional Open Source™


  Let's update a message:

             Session session = getSessionFactory().openSession();
             Transaction tx = session.beginTransaction();

             // 1 is the generated id of the first message
             Message message = session.load( Message.class, new Long(1) );

             message.setText("Greetings Earthling");

             tx.commit();
             session.close();




            select m.MESSAGE_TEXT from MESSAGES m where m.MESSAGE_ID = 1
            update MESSAGES set MESSAGE_TEXT = ‘Greetings Earthling'


  Notice that we did not explicitly call any update() method - automatic dirty
   checking gives us more flexibility when organizing data access code!
© JBoss, Inc. 2003, 2004.                                                                       12
Other configuration options
                                                                            Professional Open Source™


  Instead of using a hibernate.properties file, we may also
           – pass an instance of Properties to Configuration programmatically
           – set System properties using java -Dproperty=value
           – use a hibernate.cfg.xml file in the classpath




             The XML-based configuration is almost equivalent to the
         properties, it has some more features (cache tuning). The XML file
                  overrides the hibernate.properties options.

                            We usually prefer the XML configuration file,
                              especially in managed environments.


© JBoss, Inc. 2003, 2004.                                                                               13
Hibernate Architecture
            Hibernate Architecture
                                                                                   Professional Open Source™




                               Transaction       Query              Application

                                                Session

                                             Session Factory

                                             Configuration


                            Hibernate.cfg.xml Hibernate.properties Mapping files




© JBoss, Inc. 2003, 2004.                                                                                      14
Hibernate Architecture
            Hibernate Architecture
                                     Professional Open Source™




© JBoss, Inc. 2003, 2004.                                        15
Hibernate Architecture
                                      Professional Open Source™




© JBoss, Inc. 2003, 2004.                                         16
Hibernate Architecture
                                    Professional Open Source™




© JBoss, Inc. 2003, 2004.                                       17
SessionFactory
                                                        Professional Open Source™




            SessionFactory (org.hibernate.SessionFactory)

            A thread safe (immutable) cache of compiled
            mappings for a single database. A factory for
            Session and a client of Connection Provider.
            Might hold an optional (second-level) cache of
            data that is reusable between transactions, at a
            process- or cluster-level.



© JBoss, Inc. 2003, 2004.                                                           18
Session
                                                       Professional Open Source™




            Session (org.hibernate.Session)

            A single-threaded, short-lived object representing
            a conversation between the application and the
            persistent store

             Wraps a JDBC connection. Factory for
            Transaction. Holds a mandatory (first-level)
            cache of persistent objects, used when navigating
            the object graph or looking up objects by
            identifier.
© JBoss, Inc. 2003, 2004.                                                          19
Persistent Objects and Collections
                                                      Professional Open Source™




         Persistent objects and collections

         Short-lived, single threaded objects containing
         persistent state and business function. These
         might be ordinary JavaBeans/POJOs, the only
         special thing about them is that they are currently
         associated with (exactly one) Session. As soon as
         the Session is closed, they will be detached and
         free to use in any application layer (e.g. directly
         as data transfer objects to and from presentation).


© JBoss, Inc. 2003, 2004.                                                         20
Transient and detached objects and collections
                                                        Professional Open Source™




            Transient and detached objects and collections

            Instances of persistent classes that are not
            currently associated with a Session. They may
            have been instantiated by the application and not
            (yet) persisted or they may have been instantiated
            by a closed Session.
            .


© JBoss, Inc. 2003, 2004.                                                           21
Transaction
                                                        Professional Open Source™




            Transaction (org.hibernate.Transaction)

            (Optional) A single-threaded, short-lived object
            used by the application to specify atomic units of
            work. Abstracts application from underlying
            JDBC, JTA or CORBA transaction. A Session
            might span several Transactions in some cases.
            However, transaction demarcation, either using
            the underlying API or Transaction, is never
            optional!
            .

© JBoss, Inc. 2003, 2004.                                                           22
ConnectionProvider
                                                     Professional Open Source™




            ConnectionProvider

            (org.hibernate.connection.ConnectionProvider)
            (Optional) A factory for (and pool of) JDBC
            connections. Abstracts application from
            underlying Datasource or DriverManager. Not
            exposed to application, but can be
            extended/implemented by the developer.



© JBoss, Inc. 2003, 2004.                                                        23
TransactionFactory
                                                       Professional Open Source™




            TransactionFactory

            (org.hibernate.TransactionFactory)
            (Optional) A factory for Transaction instances.
            Not exposed to the application, but can be
            extended/implemented by the developer.




© JBoss, Inc. 2003, 2004.                                                          24
Extension Interfaces
                                                      Professional Open Source™




         Extension Interfaces
         Hibernate offers many optional extension interfaces
         you can implement to customize the behavior of your
         persistence layer.(Ex. Primary key generation,SQL
         Dialet , Caching,JDBC connection, Proxy
         creationetc.,

         Given a "lite" architecture, the application bypasses
         the Transaction/TransactionFactory and/or
         ConnectionProvider APIs to talk to JTA or JDBC
         directly.


© JBoss, Inc. 2003, 2004.                                                         25
Instance States
                                                       Professional Open Source™




            Instance states
            An instance of a persistent classes may be in one
            of three different states, which are defined with
            respect to a persistence context.




© JBoss, Inc. 2003, 2004.                                                          26
Instance States
                                                       Professional Open Source™




            Instance states
            An instance of a persistent classes may be in one
            of three different states, which are defined with
            respect to a persistence context.




© JBoss, Inc. 2003, 2004.                                                          27
Instance States
                                                       Professional Open Source™




            Transient

            The instance is not, and has never been associated
            with any persistence context. It has no persistent
            identity (primary key value).




© JBoss, Inc. 2003, 2004.                                                          28
Instance States
                                                        Professional Open Source™




            Persistent

            The instance is currently associated with a
            persistence context. It has a persistent identity
            (primary key value) and, perhaps, a corresponding
            row in the database. For a particular persistence
            context, Hibernate guarantees that persistent identity
            is equivalent to Java identity (in-memory location of
            the object).



© JBoss, Inc. 2003, 2004.                                                           29
Instance States
                                                       Professional Open Source™




         Detached

         The instance was once associated with a persistence
         context, but that context was closed, or the instance
         was serialized to another process. It has a persistent
         identity and, perhaps, a corresponding row in the
         database.

         For detached instances, Hibernate makes no
         guarantees about the relationship between persistent
         identity and Java identity.

© JBoss, Inc. 2003, 2004.                                                          30
Managed environments
                                                                            Professional Open Source™


  Hibernate can be used in an application server:

        Managed environment

                 Application                      Hibernate
                                                              Transaction
                            EJB                Session         Manager

                            EJB               Transaction
                                                               Resource
                            EJB                 Query          Manager




                            Each database has it's own SessionFactory!




© JBoss, Inc. 2003, 2004.                                                                               31
Configuration: “non-managed” environments
                                                                      Professional Open Source™


  In a “non-managed” environment (eg. Tomcat), we need a JDBC
   connection pool:
            C3P0, Proxool, custom ConnectionProvider



           Non-managed environment

                   Application               Hibernate

                             JSP          Session
                                                         Connection
                            Servlet      Transaction        Pool

                            main()         Query




© JBoss, Inc. 2003, 2004.                                                                         32
Managed environment with XML configuration file
                                                                            Professional Open Source™


               <hibernate-configuration>
                 <session-factory name="java:hibernate/SessionFactory">

                        <property name="show_sql">true</property>

                        <property name="connection.datasource">
                            java:/comp/env/jdbc/HelloDB
                        </property>

                        <property name="transaction.factory_class">
                            net.sf.hibernate.transaction.JTATransactionFactory
                        </property>

                        <property name="transaction.manager_lookup_class">
                            net.sf.hibernate.transaction.JBossTransactionManagerLookup
                        </property>

                        <property name="dialect">
                            net.sf.hibernate.dialect.PostgreSQLDialect
                        </property>

                        <mapping resource="hello/Message.hbm.xml"/>

                 </session-factory>
               </hibernate-configuration>



© JBoss, Inc. 2003, 2004.                                                                               33
Session Cache
                                                          Professional Open Source™


  To improve the performance within the Hibernate service, as well as
   your application, is to cache objects.



  By caching objects in memory, Hibernate avoids the overhead of
   retrieving them from the database each time.



  Other than saving overhead when retrieving objects, the Session
   cache also impacts saving and updating objects.



  The session interface supports a simple instance cache for each
   object that is loaded or saved during the lifetime of a given
  Session.


© JBoss, Inc. 2003, 2004.                                                             34
Session Cache
                                                                  Professional Open Source™




  Code watch :

       Session session = factory.openSession();
       Event e = (Event) session.load(Event.class, myEventId);
       e.setName(“Hibernate training”);
       session.saveOrUpdate(e);

       // later, with the same Session instance
       Event e = (Event) session.load(Event.class, myEventId);
       e.setDuration(180);
       session.saveOrUpdate(e);
       session.flush();



© JBoss, Inc. 2003, 2004.                                                                     35
The Session Cache – Common problem
                                                                 Professional Open Source™




  Don’t associate two instances of the same object with the same Session
   instance, resulting in a NonUniqueObjectException.

  Session session = factory.openSession();
  Event firstEvent = (Event) session.load(Event.class, myEventId);
  //peform some operation on firstEvent

  Event secondEvent = new Event();
  secondEvent.setId(myEventId);
  Session.save(secondEvent);

  This code opens the Session instance, loads an Event instance with a given
   ID, creates a second Event instance with the same Id, and then attempts to
   save the second Event instance, resulting in the
  NonUniqueObjectException.



© JBoss, Inc. 2003, 2004.                                                                    36
The Session Cache – Object Information
                                                        Professional Open Source™


  To see whether an object is contained in the cache
  Session.contains()




  Objects can be evicted from the cache by calling
  Session.evict()




  To clear all the objects from Session cache
  Session.clear()




© JBoss, Inc. 2003, 2004.                                                           37

More Related Content

What's hot

5050 dev nation
5050 dev nation5050 dev nation
5050 dev nationArun Gupta
 
Sql server difference faqs- 3
Sql server difference faqs- 3Sql server difference faqs- 3
Sql server difference faqs- 3Umar Ali
 
Java EE 6 and GlassFish v3: Paving the path for future
Java EE 6 and GlassFish v3: Paving the path for futureJava EE 6 and GlassFish v3: Paving the path for future
Java EE 6 and GlassFish v3: Paving the path for futureArun Gupta
 
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
TDC 2011: The Java EE 7 Platform: Developing for the CloudTDC 2011: The Java EE 7 Platform: Developing for the Cloud
TDC 2011: The Java EE 7 Platform: Developing for the CloudArun Gupta
 
GlassFish REST Administration Backend
GlassFish REST Administration BackendGlassFish REST Administration Backend
GlassFish REST Administration BackendArun Gupta
 
Hecate, Managing Authorization with RESTful XML
Hecate, Managing Authorization with RESTful XMLHecate, Managing Authorization with RESTful XML
Hecate, Managing Authorization with RESTful XMLruyalarcon
 
C fowler azure-dojo
C fowler azure-dojoC fowler azure-dojo
C fowler azure-dojosdeconf
 
Java EE 7 in practise - OTN Hyderabad 2014
Java EE 7 in practise - OTN Hyderabad 2014Java EE 7 in practise - OTN Hyderabad 2014
Java EE 7 in practise - OTN Hyderabad 2014Jagadish Prasath
 
Andrei Niculae - JavaEE6 - 24mai2011
Andrei Niculae - JavaEE6 - 24mai2011Andrei Niculae - JavaEE6 - 24mai2011
Andrei Niculae - JavaEE6 - 24mai2011Agora Group
 

What's hot (13)

5050 dev nation
5050 dev nation5050 dev nation
5050 dev nation
 
Sql server difference faqs- 3
Sql server difference faqs- 3Sql server difference faqs- 3
Sql server difference faqs- 3
 
Java EE 6 and GlassFish v3: Paving the path for future
Java EE 6 and GlassFish v3: Paving the path for futureJava EE 6 and GlassFish v3: Paving the path for future
Java EE 6 and GlassFish v3: Paving the path for future
 
Introduction to jOOQ
Introduction to jOOQIntroduction to jOOQ
Introduction to jOOQ
 
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
TDC 2011: The Java EE 7 Platform: Developing for the CloudTDC 2011: The Java EE 7 Platform: Developing for the Cloud
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
 
GlassFish REST Administration Backend
GlassFish REST Administration BackendGlassFish REST Administration Backend
GlassFish REST Administration Backend
 
Test02
Test02Test02
Test02
 
Hecate, Managing Authorization with RESTful XML
Hecate, Managing Authorization with RESTful XMLHecate, Managing Authorization with RESTful XML
Hecate, Managing Authorization with RESTful XML
 
C fowler azure-dojo
C fowler azure-dojoC fowler azure-dojo
C fowler azure-dojo
 
Java EE 7 in practise - OTN Hyderabad 2014
Java EE 7 in practise - OTN Hyderabad 2014Java EE 7 in practise - OTN Hyderabad 2014
Java EE 7 in practise - OTN Hyderabad 2014
 
Zf2 phpquebec
Zf2 phpquebecZf2 phpquebec
Zf2 phpquebec
 
09 transactions new
09 transactions new09 transactions new
09 transactions new
 
Andrei Niculae - JavaEE6 - 24mai2011
Andrei Niculae - JavaEE6 - 24mai2011Andrei Niculae - JavaEE6 - 24mai2011
Andrei Niculae - JavaEE6 - 24mai2011
 

Viewers also liked

06 association of value types
06 association of value types06 association of value types
06 association of value typesthirumuru2012
 
TNW 2012 report for PeWe group on FIIT
TNW 2012 report for PeWe group on FIITTNW 2012 report for PeWe group on FIIT
TNW 2012 report for PeWe group on FIITScooby Šalmík
 
07 association of entities
07 association of entities07 association of entities
07 association of entitiesthirumuru2012
 
Company Structure
Company StructureCompany Structure
Company StructureSturci
 
Ieframe dll forbidframing
Ieframe dll forbidframingIeframe dll forbidframing
Ieframe dll forbidframingKerry Rushton
 
01 persistence and domain modeling
01 persistence and domain modeling01 persistence and domain modeling
01 persistence and domain modelingthirumuru2012
 
Trouver des partenaires pour innover en Europe
Trouver des partenaires pour innover en EuropeTrouver des partenaires pour innover en Europe
Trouver des partenaires pour innover en EuropeAlain KHEMILI
 
12 hibernate int&cache
12  hibernate int&cache12  hibernate int&cache
12 hibernate int&cachethirumuru2012
 
Brands
BrandsBrands
BrandsSturci
 
Guide Contrefacon - Edition 2010
Guide Contrefacon - Edition 2010Guide Contrefacon - Edition 2010
Guide Contrefacon - Edition 2010Alain KHEMILI
 
Les métiers d'avenir dans l'industrie
Les métiers d'avenir dans l'industrieLes métiers d'avenir dans l'industrie
Les métiers d'avenir dans l'industrieAlain KHEMILI
 
Company Structure
Company StructureCompany Structure
Company StructureSturci
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernatehr1383
 
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
 

Viewers also liked (20)

06 association of value types
06 association of value types06 association of value types
06 association of value types
 
15 jpaql
15 jpaql15 jpaql
15 jpaql
 
TNW 2012 report for PeWe group on FIIT
TNW 2012 report for PeWe group on FIITTNW 2012 report for PeWe group on FIIT
TNW 2012 report for PeWe group on FIIT
 
15 jpa introduction
15 jpa introduction15 jpa introduction
15 jpa introduction
 
07 association of entities
07 association of entities07 association of entities
07 association of entities
 
Company Structure
Company StructureCompany Structure
Company Structure
 
Ieframe dll forbidframing
Ieframe dll forbidframingIeframe dll forbidframing
Ieframe dll forbidframing
 
01 persistence and domain modeling
01 persistence and domain modeling01 persistence and domain modeling
01 persistence and domain modeling
 
Trouver des partenaires pour innover en Europe
Trouver des partenaires pour innover en EuropeTrouver des partenaires pour innover en Europe
Trouver des partenaires pour innover en Europe
 
15 jpa
15 jpa15 jpa
15 jpa
 
12 hibernate int&cache
12  hibernate int&cache12  hibernate int&cache
12 hibernate int&cache
 
Suma ágora blog
Suma ágora blogSuma ágora blog
Suma ágora blog
 
Brands
BrandsBrands
Brands
 
Guide Contrefacon - Edition 2010
Guide Contrefacon - Edition 2010Guide Contrefacon - Edition 2010
Guide Contrefacon - Edition 2010
 
Les métiers d'avenir dans l'industrie
Les métiers d'avenir dans l'industrieLes métiers d'avenir dans l'industrie
Les métiers d'avenir dans l'industrie
 
Innovation ouverte
Innovation ouverteInnovation ouverte
Innovation ouverte
 
Company Structure
Company StructureCompany Structure
Company Structure
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
Hibernate Advance Interview Questions
Hibernate Advance Interview QuestionsHibernate Advance Interview Questions
Hibernate Advance Interview Questions
 
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
 

Similar to 02 hibernateintroduction

12 global fetching strategies
12 global fetching strategies12 global fetching strategies
12 global fetching strategiesthirumuru2012
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
10 conversations new
10 conversations new10 conversations new
10 conversations newthirumuru2012
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate IntroductionRanjan Kumar
 
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
 
Take control. write a plugin. part II
Take control. write a plugin. part IITake control. write a plugin. part II
Take control. write a plugin. part IIBaruch Sadogursky
 
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)Peter Antman
 
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
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking TourJoshua Long
 
What's new in JMS 2.0 - OTN Bangalore 2013
What's new in JMS 2.0 - OTN Bangalore 2013What's new in JMS 2.0 - OTN Bangalore 2013
What's new in JMS 2.0 - OTN Bangalore 2013Jagadish Prasath
 
What's new in Java Message Service 2?
What's new in Java Message Service 2?What's new in Java Message Service 2?
What's new in Java Message Service 2?Sivakumar Thyagarajan
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer ReferenceMuthuselvam RS
 

Similar to 02 hibernateintroduction (20)

12 global fetching strategies
12 global fetching strategies12 global fetching strategies
12 global fetching strategies
 
14 hql
14 hql14 hql
14 hql
 
Hibernate
Hibernate Hibernate
Hibernate
 
10 conversations new
10 conversations new10 conversations new
10 conversations new
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
Play 2.0
Play 2.0Play 2.0
Play 2.0
 
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)
 
Take control. write a plugin. part II
Take control. write a plugin. part IITake control. write a plugin. part II
Take control. write a plugin. part II
 
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
 
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)
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
 
Hibernate 18052012
Hibernate 18052012Hibernate 18052012
Hibernate 18052012
 
What's new in JMS 2.0 - OTN Bangalore 2013
What's new in JMS 2.0 - OTN Bangalore 2013What's new in JMS 2.0 - OTN Bangalore 2013
What's new in JMS 2.0 - OTN Bangalore 2013
 
What's new in Java Message Service 2?
What's new in Java Message Service 2?What's new in Java Message Service 2?
What's new in Java Message Service 2?
 
Ejb examples
Ejb examplesEjb examples
Ejb examples
 
jsf2 Notes
jsf2 Notesjsf2 Notes
jsf2 Notes
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
DataFX - JavaOne 2013
DataFX - JavaOne 2013DataFX - JavaOne 2013
DataFX - JavaOne 2013
 

Recently uploaded

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
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
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
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
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
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
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 

Recently uploaded (20)

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
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
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
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!
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
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
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 

02 hibernateintroduction

  • 1. Professional Open Source™ Hibernate Introduction Hello World and the Hibernate APIs © JBoss, Inc. 2003, 2004. 07/17/04 1
  • 2. Hello World I Professional Open Source™  The Hello World program prints messages – To demonstrate Hibernate, let’s define a persistent message – we use a Message persistent class, POJO style package hello; public class Message { private Long id; private String text; public String getText() { return text; } public void setText(String text) { this.text = text; } … } © JBoss, Inc. 2003, 2004. 2
  • 3. Hello World II Professional Open Source™  Messages don't have to be persistent! – we can use our persistent classes “outside” of Hibernate – Hibernate is able to “manage” persistent instances – but POJO persistent classes don't depend on Hibernate Message message = new Message("Hello World"); System.out.println( message.getText() ); © JBoss, Inc. 2003, 2004. 3
  • 4. Hello World VI Professional Open Source™  XML mapping metadata: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sf.net/hibernate-mapping-2.0.dtd"> <hibernate-mapping> <class name="hello.Message" table="MESSAGES"> <id>...</id> <property name="text" column="MESSAGE_TEXT"/> </class> </hibernate-mapping> © JBoss, Inc. 2003, 2004. 4
  • 5. Using C3P0 with hibernate.properties Professional Open Source™  Let's configure Hibernate to use C3P0 connection pooling Hibernate automatically loads hibernate.properties from a root directory of the classpath hibernate.connection.driver_class = com.mysql.jdbc.Driver hibernate.connection.url = jdbc:mysql://localhost/helloworld hibernate.connection.username = root hibernate.connection.password = root hibernate.dialect = org.hibernate.dialect.mySQLDialect hibernate.c3p0.min_size = 5 hibernate.c3p0.max_size = 20 hibernate.c3p0.timeout = 1800 hibernate.c3p0.max_statements = 50 Hibernate.c3p0.validate = true Don't forget to set the SQL dialect! © JBoss, Inc. 2003, 2004. 5
  • 6. Starting Hibernate Professional Open Source™  We create a SessionFactory using a Configuration – download and install JDBC driver in classpath – copy Hibernate and the required 3rd party libraries – chose a JDBC connection pool, customize properties – add mapping files to the Configuration – build the SessionFactory (immutable!) SessionFactory sessionFactory = new Configuration() .addResource("hello/Message.hbm.xml") .buildSessionFactory(); © JBoss, Inc. 2003, 2004. 6
  • 7. Configuring hibernate.cfg.xml Professional Open Source™  Let's configure Hibernate using hibernate.cfg.xml <hibernate-configuration> <!-- a SessionFactory instance listed as /jndi/name --> <session-factory> <!-- properties --> <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> <property name="show_sql">true</property> <property name="use_outer_join">false</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/helloworld</property> <property name="hibernate.hbm2ddl.auto">insert</property> <!-- mapping files --> <property name="cache.provider_class"> org.hibernate.cache.NoCacheProvider</property> <!-- mapping files --> <mapping resource="hello/Message.hbm.xml"/> </session-factory> </hibernate-configuration> © JBoss, Inc. 2003, 2004. 7
  • 8. Starting Hibernate Professional Open Source™  We create a SessionFactory using a Configuration – download and install JDBC driver in classpath – copy Hibernate and the required 3rd party libraries – chose a JDBC connection pool, customize properties – add mapping files to the Configuration – build the SessionFactory (immutable!) SessionFactory sessionFactory = new Configuration() .configure().buildSessionFactory(); © JBoss, Inc. 2003, 2004. 8
  • 9. Configuring Logging SQL Professional Open Source™  You have to configure the following hibernate.cfg.xml  <property name="show_sql">true</property>  <property name="format_sql">true</property> © JBoss, Inc. 2003, 2004. 9
  • 10. Hello World III Professional Open Source™  Let's persist a message with Session and Transaction: Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); Message message = new Message("Hello World"); session.save(message); tx.commit(); session.close();  Hibernate executes this SQL: insert into MESSAGES (MESSAGE_ID, MESSAGE_TEXT) values (1, 'Hello World') © JBoss, Inc. 2003, 2004. 10
  • 11. Hello World IV Professional Open Source™  Let's show all persistent messages: Session newSession = getSessionFactory().openSession(); Transaction newTransaction = newSession.beginTransaction(); Query query== newSession.createQuery("from Message"); List messages =query.list(); System.out.println( messages.size() + " message(s) found:" ); for ( Iterator iter = messages.iterator(); iter.hasNext(); ) { Message message = (Message) iter.next(); System.out.println( message.getText() ); } newTransaction.commit(); newSession.close(); select m.MESSAGE_ID, m.MESSAGE_TEXT from MESSAGES m © JBoss, Inc. 2003, 2004. 11
  • 12. Hello World V Professional Open Source™  Let's update a message: Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); // 1 is the generated id of the first message Message message = session.load( Message.class, new Long(1) ); message.setText("Greetings Earthling"); tx.commit(); session.close(); select m.MESSAGE_TEXT from MESSAGES m where m.MESSAGE_ID = 1 update MESSAGES set MESSAGE_TEXT = ‘Greetings Earthling' Notice that we did not explicitly call any update() method - automatic dirty checking gives us more flexibility when organizing data access code! © JBoss, Inc. 2003, 2004. 12
  • 13. Other configuration options Professional Open Source™  Instead of using a hibernate.properties file, we may also – pass an instance of Properties to Configuration programmatically – set System properties using java -Dproperty=value – use a hibernate.cfg.xml file in the classpath The XML-based configuration is almost equivalent to the properties, it has some more features (cache tuning). The XML file overrides the hibernate.properties options. We usually prefer the XML configuration file, especially in managed environments. © JBoss, Inc. 2003, 2004. 13
  • 14. Hibernate Architecture Hibernate Architecture Professional Open Source™ Transaction Query Application Session Session Factory Configuration Hibernate.cfg.xml Hibernate.properties Mapping files © JBoss, Inc. 2003, 2004. 14
  • 15. Hibernate Architecture Hibernate Architecture Professional Open Source™ © JBoss, Inc. 2003, 2004. 15
  • 16. Hibernate Architecture Professional Open Source™ © JBoss, Inc. 2003, 2004. 16
  • 17. Hibernate Architecture Professional Open Source™ © JBoss, Inc. 2003, 2004. 17
  • 18. SessionFactory Professional Open Source™ SessionFactory (org.hibernate.SessionFactory) A thread safe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of Connection Provider. Might hold an optional (second-level) cache of data that is reusable between transactions, at a process- or cluster-level. © JBoss, Inc. 2003, 2004. 18
  • 19. Session Professional Open Source™ Session (org.hibernate.Session) A single-threaded, short-lived object representing a conversation between the application and the persistent store Wraps a JDBC connection. Factory for Transaction. Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier. © JBoss, Inc. 2003, 2004. 19
  • 20. Persistent Objects and Collections Professional Open Source™ Persistent objects and collections Short-lived, single threaded objects containing persistent state and business function. These might be ordinary JavaBeans/POJOs, the only special thing about them is that they are currently associated with (exactly one) Session. As soon as the Session is closed, they will be detached and free to use in any application layer (e.g. directly as data transfer objects to and from presentation). © JBoss, Inc. 2003, 2004. 20
  • 21. Transient and detached objects and collections Professional Open Source™ Transient and detached objects and collections Instances of persistent classes that are not currently associated with a Session. They may have been instantiated by the application and not (yet) persisted or they may have been instantiated by a closed Session. . © JBoss, Inc. 2003, 2004. 21
  • 22. Transaction Professional Open Source™ Transaction (org.hibernate.Transaction) (Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases. However, transaction demarcation, either using the underlying API or Transaction, is never optional! . © JBoss, Inc. 2003, 2004. 22
  • 23. ConnectionProvider Professional Open Source™ ConnectionProvider (org.hibernate.connection.ConnectionProvider) (Optional) A factory for (and pool of) JDBC connections. Abstracts application from underlying Datasource or DriverManager. Not exposed to application, but can be extended/implemented by the developer. © JBoss, Inc. 2003, 2004. 23
  • 24. TransactionFactory Professional Open Source™ TransactionFactory (org.hibernate.TransactionFactory) (Optional) A factory for Transaction instances. Not exposed to the application, but can be extended/implemented by the developer. © JBoss, Inc. 2003, 2004. 24
  • 25. Extension Interfaces Professional Open Source™ Extension Interfaces Hibernate offers many optional extension interfaces you can implement to customize the behavior of your persistence layer.(Ex. Primary key generation,SQL Dialet , Caching,JDBC connection, Proxy creationetc., Given a "lite" architecture, the application bypasses the Transaction/TransactionFactory and/or ConnectionProvider APIs to talk to JTA or JDBC directly. © JBoss, Inc. 2003, 2004. 25
  • 26. Instance States Professional Open Source™ Instance states An instance of a persistent classes may be in one of three different states, which are defined with respect to a persistence context. © JBoss, Inc. 2003, 2004. 26
  • 27. Instance States Professional Open Source™ Instance states An instance of a persistent classes may be in one of three different states, which are defined with respect to a persistence context. © JBoss, Inc. 2003, 2004. 27
  • 28. Instance States Professional Open Source™ Transient The instance is not, and has never been associated with any persistence context. It has no persistent identity (primary key value). © JBoss, Inc. 2003, 2004. 28
  • 29. Instance States Professional Open Source™ Persistent The instance is currently associated with a persistence context. It has a persistent identity (primary key value) and, perhaps, a corresponding row in the database. For a particular persistence context, Hibernate guarantees that persistent identity is equivalent to Java identity (in-memory location of the object). © JBoss, Inc. 2003, 2004. 29
  • 30. Instance States Professional Open Source™ Detached The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process. It has a persistent identity and, perhaps, a corresponding row in the database. For detached instances, Hibernate makes no guarantees about the relationship between persistent identity and Java identity. © JBoss, Inc. 2003, 2004. 30
  • 31. Managed environments Professional Open Source™  Hibernate can be used in an application server: Managed environment Application Hibernate Transaction EJB Session Manager EJB Transaction Resource EJB Query Manager Each database has it's own SessionFactory! © JBoss, Inc. 2003, 2004. 31
  • 32. Configuration: “non-managed” environments Professional Open Source™  In a “non-managed” environment (eg. Tomcat), we need a JDBC connection pool: C3P0, Proxool, custom ConnectionProvider Non-managed environment Application Hibernate JSP Session Connection Servlet Transaction Pool main() Query © JBoss, Inc. 2003, 2004. 32
  • 33. Managed environment with XML configuration file Professional Open Source™ <hibernate-configuration> <session-factory name="java:hibernate/SessionFactory"> <property name="show_sql">true</property> <property name="connection.datasource"> java:/comp/env/jdbc/HelloDB </property> <property name="transaction.factory_class"> net.sf.hibernate.transaction.JTATransactionFactory </property> <property name="transaction.manager_lookup_class"> net.sf.hibernate.transaction.JBossTransactionManagerLookup </property> <property name="dialect"> net.sf.hibernate.dialect.PostgreSQLDialect </property> <mapping resource="hello/Message.hbm.xml"/> </session-factory> </hibernate-configuration> © JBoss, Inc. 2003, 2004. 33
  • 34. Session Cache Professional Open Source™  To improve the performance within the Hibernate service, as well as your application, is to cache objects.  By caching objects in memory, Hibernate avoids the overhead of retrieving them from the database each time.  Other than saving overhead when retrieving objects, the Session cache also impacts saving and updating objects.  The session interface supports a simple instance cache for each object that is loaded or saved during the lifetime of a given  Session. © JBoss, Inc. 2003, 2004. 34
  • 35. Session Cache Professional Open Source™  Code watch :  Session session = factory.openSession();  Event e = (Event) session.load(Event.class, myEventId);  e.setName(“Hibernate training”);  session.saveOrUpdate(e);  // later, with the same Session instance  Event e = (Event) session.load(Event.class, myEventId);  e.setDuration(180);  session.saveOrUpdate(e);  session.flush(); © JBoss, Inc. 2003, 2004. 35
  • 36. The Session Cache – Common problem Professional Open Source™  Don’t associate two instances of the same object with the same Session instance, resulting in a NonUniqueObjectException.  Session session = factory.openSession();  Event firstEvent = (Event) session.load(Event.class, myEventId);  //peform some operation on firstEvent  Event secondEvent = new Event();  secondEvent.setId(myEventId);  Session.save(secondEvent);  This code opens the Session instance, loads an Event instance with a given ID, creates a second Event instance with the same Id, and then attempts to save the second Event instance, resulting in the  NonUniqueObjectException. © JBoss, Inc. 2003, 2004. 36
  • 37. The Session Cache – Object Information Professional Open Source™  To see whether an object is contained in the cache  Session.contains()  Objects can be evicted from the cache by calling  Session.evict()  To clear all the objects from Session cache  Session.clear() © JBoss, Inc. 2003, 2004. 37