0

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 ?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Not to mention that this is a "static" method being called probably from a JSP. Dropping the session factory will recreate the inner connection pool, so no pooling too.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.