Himanshu Matta
Himanshu Matta

Reputation: 73

Hibernate select query taking time

I am using jsp and hibernate. Below is my function -

public static List<user_detail>  getData(String username)
    {
       List<user_detail> list = null;
        try{
        Session session=newConfiguration().configure().buildSessionFactory().openSession(); 
        Transaction tx=session.beginTransaction();
        Query query = session.createQuery("from user_detail where username = :user");
        query.setParameter("user", username);
        list =  query.list();
        Iterator<user_detail> itr=list.iterator();  
        while(itr.hasNext()){  
                  descLog("Parameters"+itr.next()+"\n");
        }
        }
        catch(Exception e)
        {
            writeLog(e);
        }


        return list;
    }

I call this function from my jsp page. But the problem is every time this function takes around 5 second. I have only one record in table. Why this is taking time ? How to reduce this time ?

Upvotes: 0

Views: 116

Answers (1)

JB Nizet
JB Nizet

Reputation: 692201

There are many things wrong in the above code:

  1. You're creating a new SessionFactory every time it's called. A SessionFactory should be created once and only once, and be reused for the complete life of the application. Creating a SessionFactory implies reading the configuration, analyze it, build the metamodel of all the entities, check it against the database schema, etc.
  2. You're starting a transaction, but never commit it or rollback it
  3. You're opening a session, but neglect to close it. That means a memory leak, and it also means that the underlying database connection is never closed.
  4. You don't respect the Java naming conventions. The class should be named UserDetail, not user_detail.

I suggest you re-read the Hibernate reference documentation from scratch.

Upvotes: 2

Related Questions