Hibernate 5: sessionFactory is null

10,367

Solution 1

The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above try to write the configuration like this:

Configuration configuration = new Configuration().configure();
configuration.configure("your_path_hibernate_.cfg.xml");
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
 sessionFactory = configuration.buildSessionFactory(ssrb.build());

Solution 2

When I updated my Hibernate code from v4.1.8 to v5.0.6 I too had a problem with my SessionFactory instance being null. By printing the stack trace I was able to figure out that I needed to include the optional c3p0 jars in my build path.

My first suggestion would be to print the stack trace directly from your catch block. The trace will provide a good starting point on your way toward resolution. So your catch block would look like:

catch (Exception e) {
        // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
        // so destroy it manually.
        StandardServiceRegistryBuilder.destroy( registry );
        e.printStackTrace();
    }

However, I notice that you don't have a hibernate.dialect property defined in your configuration file. While this property is not mandatory the Hibernate User Guide notes that there may be "some reason" hibernate is not able to determine which dialect you are using. My second suggestion would be to define your database dialect directly in your configuration file with the hibernate.dialect setting.

Since your original configuration file post suggests that you are making use of the MySQL database dialect, try adding in this dialect property node to the session-factory node:

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

If you are using MySQL 5.x then use

<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

Make sure that the optional c3p0 jars are in your build path.

Best of luck!

Solution 3

private static SessionFactory sessionFactory = createSessionFactory();

private static SessionFactory createSessionFactory() {
    if (sessionFactory == null) {
        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()                 .configure("hibernate.cfg.xml").build();
        Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();
        sessionFactory = metaData.getSessionFactoryBuilder().build();
    }
    return sessionFactory;
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

public static void shutdown() {
    sessionFactory.getCurrentSession().close();
}
Share:
10,367
ziiweb
Author by

ziiweb

Ziiweb is a web agency on creating websites and web applications. We also offer marketing online services (SEO/PPC) to promote your business through search engines and social networks. We always bet for the last and best web technologies: HTML5, CSS3, jQuery, PHP5 and symfony (all releases).

Updated on June 05, 2022

Comments

  • ziiweb
    ziiweb almost 2 years

    Im getting a null value for sessionFactory variable at this line:

    sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
    

    This is the whole class:

    import javax.imageio.spi.ServiceRegistry;
    import javax.transaction.Transaction;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.boot.MetadataSources;
    import org.hibernate.boot.registry.StandardServiceRegistry;
    import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
    import org.hibernate.cfg.Configuration;
    
    import ch.makery.model.Employee;  
    
    public class HelloWorld {
        protected void setUp() throws Exception {
        }
    
        public static void main(String[] args) {
    
            SessionFactory sessionFactory = null;
    
            // A SessionFactory is set up once for an application!
            final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                    .configure() // configures settings from hibernate.cfg.xml
                    .build();
            try {
                sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
            }
            catch (Exception e) {
                // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
                // so destroy it manually.
                StandardServiceRegistryBuilder.destroy( registry );
            }
    
            Session session = sessionFactory.openSession();
            //employee = new Employee();
    
           session.beginTransaction();
           session.save(new Employee());
           session.getTransaction().commit();
           session.close();
        }
    }
    

    This is my Hibernate related files:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
            "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
        <session-factory>
            <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="hibernate.connection.password">manolete</property>
            <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/employee</property>
            <property name="hibernate.connection.username">root</property>
            <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
            <property name="hbm2ddl.auto">create</property>
            <mapping resource="src/ch/makery/model/Employee.hbm.xml" />
        </session-factory>
    </hibernate-configuration>
    
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <!-- Generated 14-dic-2015 21:00:04 by Hibernate Tools 3.4.0.CR1 -->
    <hibernate-mapping>
        <class name="ch.makery.model.Employee" table="EMPLOYEE">
            <id name="id" type="int">
                <column name="ID" />
                <generator class="assigned" />
            </id>
            <property name="firstName" type="java.lang.String">
                <column name="FIRSTNAME" />
            </property>
            <property name="lastName" type="java.lang.String">
                <column name="LASTNAME" />
            </property>
        </class>
    </hibernate-mapping>
    
    package ch.makery.model;
    
    public class Employee {  
        private int id;  
        private String firstName,lastName;  
    
        public int getId() {  
            return id;  
        }  
        public void setId(int id) {  
            this.id = id;  
        }
    
        public String getFirstName() {  
            return firstName;  
        }  
        public void setFirstName(String firstName) {  
            this.firstName = firstName;  
        }   
    
        public String getLastName() {  
            return lastName;  
        }  
        public void setLastName(String lastName) {  
            this.lastName = lastName;  
        }   
    
    }
    

    Im not using Spring since Im just creating a desktop application.

  • ziiweb
    ziiweb over 8 years
    but the quick start says buildSessionFactory() it is not deprecated: docs.jboss.org/hibernate/orm/5.0/quickstart/html
  • Abdelhak
    Abdelhak over 8 years
    @ziiweb take a look at this link
  • Scott Weldon
    Scott Weldon over 7 years
    Welcome to Stack Overflow! While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Flaggers / reviewers: For code-only answers such as this one, downvote, don't delete!