0

Previously I used JDBC in my application and it was running very fast, but I have modified it to use Hibernate which made it too slow, especially when it needs to open a page that has a dropdown box in it. It takes much longer in compare to JDBC, to open this kind of pages.

If I try to access a table with foreign keys it takes much longer.

My server is GlassFish and I am usingfollowing version of hibernate.

  <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.1.10.Final</version>
            <type>jar</type>
        </dependency>

The questions are why is it to slow in compare to JDBC and do I need to have the following lin before each session.beginTransaction() ?

    session = HibernateUtil.getSessionFactory().openSession();

Take the following one as an example, it has a dropdown box that need to be populated once the page is opened.

HibernateUtil.java

package com.myproject.util;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {

    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    private static SessionFactory configureSessionFactory() {
        try {
            System.out.println("1");

            Configuration configuration = new Configuration();
            configuration.configure();
            serviceRegistry = new 
                ServiceRegistryBuilder()
                  .applySettings(configuration.getProperties())
                  .buildServiceRegistry();
            System.out.println("2");

            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            System.out.println("3");

            return sessionFactory;
        } catch (HibernateException e) {
            System.out.append("** Exception in SessionFactory **");
            e.printStackTrace();
        }
        return sessionFactory;
    }

    public static SessionFactory getSessionFactory() {
        return configureSessionFactory();
    }
}

MyClassModel.java

public class MyClassModel extends HibernateUtil {

    private Session session;

     public Map populatedropdownList() {
        Map map = new HashMap();
        session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        List<MyListResult> temp = null;
        try{

              temp = retrieveItems();
              System.err.println("size:" + temp.size());
              for(int i=0;i<temp.size();i++){
                  map.put(temp.get(i).getId(),temp.get(i).getName());
              }
        session.getTransaction().commit();
        session.close();
        return map;
    }catch(Exception e){
        e.printStackTrace();
    }
    return map;
   }



private List <MyListResult> retrieveItems(){
              Criteria criteria = session.createCriteria(MyTable.class, "MyTable");
                ProjectionList pl = Projections.projectionList();
                pl.add(Projections.property("MyTable.id").as("id"));
                pl.add(Projections.property("MyTable.name").as("name"));
                criteria.setProjection(pl);

                criteria.setResultTransformer(new 
                        AliasToBeanResultTransformer(MyListResult.class));
                return criteria.list();
    }

MyListResult.java

public class MyListResult implements Serializable {
    private int id;
    private String Name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return Name;
    }

    public void setName(String Name) {
        this.Name = Name;
    }    

}

Hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">
            com.mysql.jdbc.Driver
        </property>
        <property name="connection.url">
            jdbc:mysql://localhost:3306/MyDatabase
        </property>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">
            org.hibernate.dialect.MySQLDialect
        </property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">
            org.hibernate.cache.NoCacheProvider
        </property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

                <mapping class="com.MyProject.MyTable" />


    </session-factory>

</hibernate-configuration>

Console is as following

INFO: in myform
INFO: 1
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
INFO: HHH000041: Configured SessionFactory: null
INFO: 2
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
INFO: HHH000115: Hibernate connection pool size: 1
INFO: HHH000006: Autocommit mode: false
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL 
[jdbc:mysql://localhost:3306/MyDatabase]
INFO: HHH000046: Connection properties: {user=root, password=****}
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
INFO: HHH000397: Using ASTQueryTranslatorFactory
INFO: HHH000228: Running hbm2ddl schema update
INFO: HHH000102: Fetching database metadata
INFO: HHH000396: Updating schema
INFO: HHH000261: Table found: MyDatabase.MyTable
INFO: HHH000037: Columns: [id, name, age, xx, yy]
INFO: HHH000126: Indexes: [primary]
INFO: HHH000232: Schema update complete
INFO: Hibernate: select this_.id as y0_, this_.name as y1_ from MyTable this_
SEVERE: size:4
6
  • @Lion would that be a reason of slowness ? do you know of any working sample or tutorial ?
    – J888
    Jun 20, 2013 at 4:47
  • 2
    Oh! sorry, I deleted my comment because I was talking about the Spring framework that probably you're not using.
    – Lion
    Jun 20, 2013 at 4:52
  • @Lion no I am using struts2
    – J888
    Jun 20, 2013 at 4:53
  • 2
    what is the negative vote for?
    – J888
    Jun 20, 2013 at 5:10
  • 1
    Ah! that I didn't do +1.
    – Lion
    Jun 20, 2013 at 5:23

2 Answers 2

1

Usually in the application you shouldn't build the session factory each time when you need the session. That's what actually needed by application to use the hibernate. If you want to manage the session manually then you write the HibernateUtil making it singleton. Initially, build the session factory in the static initializer block

  private static final ThreadLocal<Session> threadLocal = new ThreadLocal<>();
  private static SessionFactory sessionFactory;

  static {
    try {
      sessionFactory = configureSessionFactory();
    } catch (Exception e) {
      System.err.println("%%%% Error Creating SessionFactory %%%%");
      e.printStackTrace();
    }
  }

  private HibernateUtil() {
  }

  public static SessionFactory getSessionFactory() {
    return sessionFactory;
  }

  public static Session getSession() throws HibernateException {
    Session session = threadLocal.get();

    if (session == null || !session.isOpen()) {
      if (sessionFactory == null) {
        rebuildSessionFactory();
      }
      session = (sessionFactory != null) ? sessionFactory.openSession() : null;
      threadLocal.set(session);
    }

    return session;
  }

  public static void rebuildSessionFactory() {
    try {
      sessionFactory = configureSessionFactory();
    } catch (Exception e) {
      System.err.println("%%%% Error Creating SessionFactory %%%%");
      e.printStackTrace();
    }
  }

  public static void closeSession() throws HibernateException {
    Session session = (Session) threadLocal.get();
    threadLocal.set(null);

    if (session != null) {
      session.close();
    }
  }

think that's enough addition to your code to run your application.

0

While I don't have any direct experience with Hibernate, I do with NHibernate, which is modeled after the Java version, so this should still be correct...

Building up the SessionFactory takes time, all the more so since, if I'm reading the configuration right, you're having it check for schema changes between your models and the database when it does start.

What you should do instead is create the SessionFactory once on startup (or upon the first use of data access, depending on when you want to pay the cost of setting up Hibernate) and use that through the lifetime of your app.

What I tend to do is something roughly like this (rough psuedocode, since my Java is rusty):

Session getSession()
{
    if(sessionFactory == null)
       buildSessionFactory()

    return sessionFactory.OpenSession()
}

(Of course this doesn't take into account any possible race conditions with threading). This should hopefully see a rather large performance boost. Keep in mind that ORMs are almost never as fast as hand-coded SQL due to the additional mapping layers, but it's a trade off between performance and ease of coding.

1
  • Thanks for the answer, does that mean I need to remove "check for schema" part and have this code in a class?
    – J888
    Jun 20, 2013 at 5:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.