【问题标题】:How to create SessionFactory using Hibernate4 and Spring?如何使用 Hibernate4 和 Spring 创建 SessionFactory?
【发布时间】:2015-07-31 15:57:20
【问题描述】:

我在尝试管理休眠以使用 spring 时遇到问题。我不知道如何在我的代码上启动 Session 类。 NetBeans 一直说变量 sessionFactory 尚未初始化。
当我尝试 sessionFactory.openSession(); 时,我遇到的问题是 HibernateTest.java;

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

结构(没有代表上传图片,所以复制如下):
-休眠课程
+网页 -源码包
-com.course.entity
性别.java
-com.source.test
HibernateTest.java
-其他来源
-src/main/资源
-默认包
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>

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

【问题讨论】:

    标签: java spring hibernate sessionfactory


    【解决方案1】:

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

    发生的只是您声明一个休眠会话工厂,不初始化它,并尝试使用它。所以是的,Netbeans 是对的,变量 sessionFactory 永远不会在您的代码中初始化。

    要解决这个问题,你必须先选择是否要直接使用Hibernate然后阅读并遵循Hibernate教程,还是使用Spring + Hibernate并阅读并遵循Spring教程。

    Hibernate 手册的教程表格建议使用类似于:

    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。

    【讨论】:

    • 非常感谢。我打算使用 Spring,这样我就可以为整个程序只使用一个 SessionFactory,因为 SessionFactory 需要大量的系统资源。
    【解决方案2】:

    您需要使用@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 代替手动事务管理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-23
      • 2021-02-13
      • 2015-05-02
      • 2012-10-16
      • 2014-10-24
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      相关资源
      最近更新 更多