如何使用 Hibernate4 和 Spring 创建 SessionFactory?

How to create SessionFactory using Hibernate4 and Spring?

我在尝试管理休眠以与 spring 一起工作时遇到问题。我不知道如何在我的代码上启动会话 class。 NetBeans 让我说变量 sessionFactory 尚未初始化。
当我尝试 sessionFactory.openSession();

时,我遇到的问题是 HibernateTest.java

这里是工程的结构和代码,希望大家能帮帮我,谢谢。 PS。我正在使用 NetBeans 8.0.1

结构(没有代表上传图片所以复制如下):
-休眠课程
+网页 -源包
-com.course.entity
Gender.java
-com.source.test
HibernateTest.java
-其他来源
-src/main/resources
-<>默认包<>
hibernate.cfg.xml
spring.xml
+依赖关系
+Java 依赖项
+项目文件

spring.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();
    }
}

您需要使用 @Autowired 将 SessionFatory 作为 spring 管理的 bean 注入,或者从 Spring 应用程序上下文中获取它:

public class HibernateTest {

    public static void main(String[] args) throws ParseException {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        SessionFactory sessionFactory = context.getBean("sessionFactory", SessionFactory.class);

        Gender gender = new Gender();
        gender.setCodeGender(3);
        gender.setGender("Test");      

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(gender);
        session.getTransaction().commit();
        session.close();
    }
}

此外,您可以使用 @Transational 而不是手动事务管理。

首先,您的示例中根本没有使用 spring,因为 HibernateTest 中的 main 不会尝试 bootstrap 一个 Spring 应用程序上下文。

只是您声明一个休眠会话工厂,不初始化它,然后尝试使用它。所以是的,Netbeans 是正确的,变量 sessionFactory 从未在您的代码中初始化。

要修复它,您必须首先选择是否要直接使用 Hibernate,然后阅读并遵循 Hibernate 教程,使用 Spring + Hibernate 并阅读并遵循 Spring 教程。

教程形式的 Hibernate 手册建议使用类似于 util class:

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

}

并使用它来创建 Hibernate 会话工厂。但这同样不使用 Spring.