注册 登录
编程论坛 JAVA论坛

hibernate中的sessionFactory异常

逆水寒刘 发布于 2015-12-22 16:19, 2348 次点击
程序代码:
public static Session currentSession()throws HibernateException{
             Session session=(Session)threadLocal.get();
              if(session==null){
                  
                  if(sessionFactory==null){
                      try{
                      cfg.configure(CONFIG_FILE_LOCATION);
                      sessionFactory=cfg.configure().buildSessionFactory();
                      }catch(Exception e){
                      System.err.println("%%%% Error Creating SessionFatory %%%%");
                  }
                      }
                  session=sessionFactory.openSession();//提示这里出错,mian函数报空指针异常,不知道怎么办,程序检查正确,但一运行就出错。
                  threadLocal.set(session);
              }
              return session;
          }

            
7 回复
#2
逆水寒刘2015-12-22 19:32
程序代码:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE Hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate. <session-factory>
        <property name="myeclipse.connection.profile">JDBC for MySQL</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/demo</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <mapping resource="com/demo/hibernate/beans/po/User.hbm.xml" /></session-factory></Hibernate-configuration>
这是hibernate.cfg.xml

//HibernateSessionfactory代码
程序代码:
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
          private static String CONFIG_FILE_LOCATION="/hibernate.cfg.xml";
          private static final ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
          private static final Configuration cfg=new Configuration();
          private static SessionFactory sessionFactory;
         
          public static Session currentSession()throws HibernateException{
             Session session=(Session)threadLocal.get();
              if(session==null){
                  
                  if(sessionFactory==null){
                      try{
                      cfg.configure(CONFIG_FILE_LOCATION);
                      sessionFactory=cfg.configure().buildSessionFactory();
                      }catch(Exception e){
                      System.err.println("%%%% Error Creating SessionFatory %%%%");
                  }
                      }
                  session=sessionFactory.openSession();
                  threadLocal.set(session);
              }
              return session;
          }
         
          public static void closeSession(){
              Session session=(Session)threadLocal.get();
              threadLocal.set(null);
              if(session!=null){
                  session.close();
              }
          }
}


//User.hbm.xml
程序代码:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE Hibernate-maping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate. package="com.demo.hibernate.beans.po">
    <class name="User" table="user">
        <id name="id" column="id" type="integer">
            <generator class="native"></generator>
        </id>
        <property name="username" column="username" type="string"></property>
        <property name="password" column="password" type="string"></property>
        <property name="email" column="email" type="string"></property></class></Hibernate-maping>

只有本站会员才能查看附件,请 登录
只有本站会员才能查看附件,请 登录
#3
紫月一殇雪2015-12-22 20:00
第一段代码中的try块
              
try{
                      cfg.configure(CONFIG_FILE_LOCATION);      //因为你这里加载过一次了所以下面就没必要加载了
                      sessionFactory =  cfg.buildSessionFactory(); // cfg.configure().buildSessionFactory();   
                      }




[此贴子已经被作者于2015-12-22 20:18编辑过]

#4
逆水寒刘2015-12-22 20:17
请大神给指点一下。初学hibernate。
#5
逆水寒刘2015-12-22 20:20
回复 3楼 紫月一殇雪
还是不行啊
#6
紫月一殇雪2015-12-22 20:23
程序代码:
package cn.jbit.blog.sessionFactory;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.AnnotationConfiguration;

/**

 * Configures and provides access to Hibernate sessions, tied to the

 * current thread of execution.  Follows the Thread Local Session

 * pattern, see {
@link http:// }.

 
*/
public class HibernateSessionFactory {

    /**
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file.
     * The default classpath location of the hibernate config file is
     * in the default package. Use #setConfigFile() to update
     * the location of the configuration file for the current session.   
     
*/
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static org.hibernate.SessionFactory sessionFactory;
   
    private static Configuration configuration = new AnnotationConfiguration();   
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    private static String configFile = CONFIG_FILE_LOCATION;

    static {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }
    private HibernateSessionFactory() {
    }
   
    /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  
@return Session
     *  
@throws HibernateException
     
*/
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

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

        return session;
    }

    /**
     *  Rebuild hibernate session factory
     *
     
*/
    public static void rebuildSessionFactory() {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }

    /**
     *  Close the single hibernate session instance.
     *
     *  
@throws HibernateException
     
*/
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

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

    /**
     *  return session factory
     *
     
*/
    public static org.hibernate.SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     *  return session factory
     *
     *    session factory will be rebuilded in the next call
     
*/
    public static void setConfigFile(String configFile) {
        HibernateSessionFactory.configFile = configFile;
        sessionFactory = null;
    }
    /**
     *  return hibernate configuration
     *
     
*/
    public static Configuration getConfiguration() {
        return configuration;
    }

}
#7
紫月一殇雪2015-12-22 20:23
自己慢慢比对
#8
逆水寒刘2015-12-22 22:02
回复 7楼 紫月一殇雪
谢谢回帖,但即使复制粘贴过去,即使还是有些异常。
1