How to create SessionFactory using Hibernate4 and Spring?
First, you are not using spring at all in your example, because main
in HibernateTest
does not try to bootstrap a Spring application context.
What happens is simply that you declare a hibernate session factory, do not initialize it, and try to use it. So yes Netbeans is right, variable sessionFactory
is never initialized in your code.
To fix it, you must first choose whether you want to directly use Hibernate and then read and follow a Hibernate tutorial, of use Spring + Hibernate and read and follow a Spring tutorial.
The tutorial form Hibernate manual recommends to use an util class similar to :
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().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;
}
}
and use it to create the Hibernate session factory. But again this does not use Spring.
Related videos on Youtube
Evandro
Updated on June 04, 2022Comments
-
Evandro almost 2 years
I am having issues trying to manage hibernate to work with spring. I don't know how to initiate a Session class on my code. NetBeans keep me saying that the variable sessionFactory has not been initialized.
The problem I am having is on HibernateTest.java when I try sessionFactory.openSession();Here is the structure of the project and the code, I hope you can help me, thank you. PS. I am using NetBeans 8.0.1
Structure (Dont have rep to upload an image so ill copy as it follows):
-Hibernate Course
+Web Pages -Source Packages
-com.course.entity
Gender.java
-com.source.test
HibernateTest.java
-Other Sources
-src/main/resources
-<>default package<>
hibernate.cfg.xml
spring.xml
+Dependencies
+Java Dependencies
+Project filesspring.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.3.xsd"> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:hibernate.cfg.xml" /> </bean> <tx:annotation-driven /> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="userDao" class="com.course.entity.Gender"> <constructor-arg> <ref bean="sessionFactory" /> </constructor-arg> </bean> </beans>
Hibernate.cfg.xml:
<?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.dialect">org.hibernate.dialect.PostgreSQL9Dialect</property> <property name="hibernate.connection.driver_class">org.postgresql.Driver</property> <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/Hibernate</property> <property name="hibernate.connection.username">postgres</property> <property name="hibernate.connection.password">admin</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping class="com.course.entity.Gender"/> </session-factory> </hibernate-configuration>
Gender.java
package com.course.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; @Entity public class Gender { @Id @SequenceGenerator(name = "ggender_cod_seq", initialValue = 0) @GeneratedValue(generator = "gender_cod_seq", strategy = GenerationType.AUTO) private int codeGender; private String gender; public int getCodeGender() { return codeGender; } public void setCodeGender(int codeGender) { this.codeGender = codeGender; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
HibernateTest.java
package com.source.test; import com.course.entity.Gender; import java.text.ParseException; import org.hibernate.Session; import org.hibernate.SessionFactory; public class HibernateTest { public static void main(String[] args) throws ParseException { Gender gender = new Gender(); gender.setCodeGender(3); gender.setGender("Test"); SessionFactory sessionFactory; Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(gender); session.getTransaction().commit(); session.close(); } }
-
Evandro almost 9 yearsThank you very much. I am planning to use Spring so then I can have just one SessionFactory for the whole program, as SessionFactory demands so much resources of the system.