我无法在Hibernate 5.1.0中获得SessionFactory。获取SessionFactory obj

时间:2016-05-12 12:45:33

标签: java hibernate

Image

错误:

1) AdminModel.java - 模型类。

2) HibernateUtil.java 促进了Hibernate数据库连接。

3) AdminDAO.java - 你知道这些是什么......我会挽救痛苦来解释......哦,是的......我已经度过了几天的痛苦bug ... trynna debug ...我已经有了截止日期......如果你的家伙可以帮助我,这将是一个很大的问题......

public class AdminModel {
    private int adminID;
    private String username;
    private String password;

    public int getAdminID() {
        return adminID;
    }
    public void setAdminID(int adminID) {
        this.adminID = adminID;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }


}
  

HibernateUtil.java

public class HibernateUtil {

    public static  SessionFactory sessionFactory;

    static {
        try {

/*                File f=new File("O:/@workspace/@eclipse/ekatabookstore.com/src/hibernate.cfg.xml");
                sessionFactory =new Configuration().configure(f).buildSessionFactory();
*/                
 /****OR****/

            String hibernatePropsFilePath = "O:/@workspace/@eclipse/ekatabookstore.com/src/hibernate.cfg.xml";
            File hibernatePropsFile = new File(hibernatePropsFilePath);
            Configuration configuration = new Configuration();
            configuration.configure(hibernatePropsFile);
            configuration.addResource("ekatabookstore.hbm.xml");
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); 
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        } catch (Exception ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            //throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session openSession() {
        return HibernateUtil.sessionFactory.openSession();
        //return sessionFactory.getCurrentSession();
    }
}
  

AdminDAO.java

    public AdminDAO(AdminModel adminUserObj) {
public void createAdmin() {
        /*
         * CRUD operation of HIBERNATE C-->Create SessionFactory Object is a
         * heavy object and takes up huge resources, so it is better to create
         * only one object and share it where needed.
         */
        SessionFactory sessionFactoryObj = HibernateUtil.sessionFactory;
//      System.out.println(sessionFactoryObj.getClass().getName());     
        Session session = sessionFactoryObj.openSession();
        session.beginTransaction();// Transaction Started
        session.save(adminObj);// SAVED
        session.getTransaction().commit();// Transaction Ended
        System.out.println("!!!SUCCESSFUL CREATE!!!");
        session.close();// CLOSE session resource of Hibernate

        Notification.notificationMsg = "ADMIN CREATE - SUCCESSFUL!";
    }
}

hibernate.cfg.xml中

<?xml version='1.0' encoding='utf-8'?>
<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/ekatabookstoreDB</property>
        <property name="connection.username">xyz</property>
        <property name="connection.password">xyz</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>   

      <!-- Enable Hibernate's automatic session context management -->  
        <property name="current_session_context_class">thread</property>   

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <!-- <property name="hbm2ddl.auto">create</property> -->
        <property name="hbm2ddl.auto">update</property>

        <mapping resource="ekatabookstore.hbm.xml" /> 

    </session-factory>

</hibernate-configuration>

hbn.properties hiberNateCfgFileName = hibernate.cfg.xml中

ekatabookstore.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
     <class name="com.ekatabookstore.layer.service.model.AdminModel" table="admin">
        <id name="adminID" type="integer" column="id_admin">
            <generator class="assigned" />           
        </id>

        <property name="username" type="string" column="username" not-null="true" />
        <property name="password" type="string" column="password" not-null="true" />        
    </class>
</hibernate-mapping>

2 个答案:

答案 0 :(得分:0)

如果您正在使用spring,请在sessionfactory上添加autowire或从应用程序上下文中获取它。您可以使用以下代码

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextProvider implements ApplicationContextAware{

   private static ApplicationContext context;

   public static ApplicationContext getApplicationContext() {
      return context;
   }

   @Override
   public void setApplicationContext(ApplicationContext ac)
           throws BeansException {
       context = ac;
   }
}

您可以在代码中的任何位置使用此类,例如

ApplicationContextProvider.getApplicationContext().getBean("sessionFactory");

答案 1 :(得分:0)

请尝试使用以下代码创建sessionfactory

final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure() // configures settings from hibernate.cfg.xml
    .build();
try {
    sessionFactory = new MetadataSources( registry).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
    StandardServiceRegistryBuilder.destroy( registry );
}

希望这有帮助。

相关问题