无法对类型为HibernateUtil的非静态方法getSessionFactory()进行静态引用

时间:2015-06-04 05:17:35

标签: java mysql hibernate orm sessionfactory

尝试使用 Hibernate Struts2 显示来自 MySQL 数据库的数据,我可以将数据添加到数据库中,并且值正在增加已更新但我无法在 jsp 页面中显示。

错误:无法对HibernateUtil类型的非静态方法getSessionFactory()进行静态引用

我的页面是......

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;
    }

}

1 个答案:

答案 0 :(得分:2)

你需要改变这个:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();

到此:

Session session = HibernateUtils.getSessionFactory().getCurrentSession();

该类名为HibernateUtils,而不是HibernateUtil