Hibernate Basics

Hibernate is a framework that takes the burden of object persistence in a relational database. With a bit of configuration, developers can concentrate on the object for data persistence while Hibernate takes care of the object-relational mismatch problem. There are three steps involved in using Hibernate:
  • Configuring the Session Factory and datasources
  • Setting the Hibernate properties
  • Creating the POJO and relevant mappings



    First, Hibernate requires a configuration file, called hibernate.properties, from where it can create a Session Factory.  In this file we define the Datasource,username,password,URL,Driver information...etc

    example :

    hibernate.dialect org.hibernate.dialect.MySQL5Dialect
    hibernate.connection.driver_class com.mysql.jdbc.Driver
    hibernate.connection.url jdbc:mysql://localhost:3306/JSDATA
    hibernate.connection.username user
    hibernate.connection.password password
    hibernate.current_session_context_class thread
    hibernate.show_sql false
     
     
    Note that you can define the same properties using a XML file,usually called 
    as hibernate.cfg.xml. 
    
    
    
    
    The next step is to create a mapping file that maps the Objects classes to the Database table 
    columns.
     
     
    
    
    
      
        
          
        
        
        
        
        
        
      
    
     
    The class attribute declares a fully qualified name of the Java object while table attribute points to the corresponding TRADES table.


    Now that our configuration and mapping is done, it is time to write a simple client:
    public class PlainHibernateTest {
      private SessionFactory factory = null;
      private Configuration configuration = null;
      public PlainHibernateTest() {
        configuration = new Configuration();
        configuration.addFile("Trade.hbm.xml");
        factory = configuration.buildSessionFactory();
      }
    
      private void testInsert(Trade t) {
        Session session = factory.getCurrentSession();
        session.beginTransaction();
        session.save(t);
        session.getTransaction().commit();
        System.out.println("Inserted Trade"+t.getId());
      }
    
      public static void main(String[] args) {
        Trade t = DomainUtil.createDummyTrade();
        PlainHibernateTest test = new PlainHibernateTest();
        test.testInsert(t);
      }
    }


     
  • As you can see above, the Configuration object is created first. Behind the scenes, the framework reads the hibernate.properties, file which is available in the classpath and creates the Configuration object. You can provide the respective mapping files by invoking the appropriate method toward the configuration. The Configuration object is then used to create a SessionFactory. Once you have a SessionFactory, create a Session from it and start your work. The Trade is persisted into the database when you call save() on a session.