Tried to display the data from MySQL Database using Hibernate and Struts2, I can add the data into the database and the values are getting updated but i cannot display it in jsp page.
Error: Cannot make a static reference to the non-static method getSessionFactory() from the type HibernateUtil
Here my pages are..
HibernateUtils.java
package com.stg.shdb2.utils;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtils {
private static final SessionFactory sessionFactory=buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
DataConnect.java
package com.stg.shdb2.dao;
import java.util.List;
import net.sf.gilead.core.hibernate.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.apache.cxf.service.invoker.SessionFactory;
import com.stg.shdb2.beans.User;
import com.stg.shdb2.utils.HibernateUtils;
public class DataConnect {
Session sess;
public void insertDetails(User user){
try{
sess = (Session) HibernateUtils.getSessionFactory();
Transaction tx = sess.beginTransaction();
sess.save(user);
System.out.println("Data Inserted in user_details");
tx.commit();
sess.close();
}
catch(Exception exep){
exep.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public List<User> list() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<User> user = null;
try {
user = (List<User>) session.createQuery("from user_data").list();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return user;
}
}
You need to change this:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
to this:
Session session = HibernateUtils.getSessionFactory().getCurrentSession();
The class is named HibernateUtils
, not HibernateUtil
.