java - 如何使用 Hibernate4 和 Spring 创建 SessionFactory?

标签 java spring hibernate sessionfactory

我在尝试管理 hibernate 以与 spring 一起工作时遇到问题。我不知道如何在我的代码上启动 session 类。 NetBeans 让我说变量 sessionFactory 尚未初始化。
当我尝试 sessionFactory.openSession(); 时,我遇到的问题是在 HibernateTest.java 上;

下面是工程的结构和代码,希望大家能帮帮我,谢谢。 附言。我正在使用 NetBeans 8.0.1

结构(没有代表上传图像,所以复制如下):
- hibernate 类(class)
+网页 -源码包
-com.course.entity
性别.java
-com.source.test
hibernate 测试.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;
    } 
}

hibernate 测试.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();
    }
}

最佳答案

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

所发生的只是您声明一个 hibernate session 工厂,不初始化它,并尝试使用它。所以是的,Netbeans 是正确的,变量 sessionFactory 从未在您的代码中初始化。

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

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

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 session 工厂。但这同样没有使用 Spring。

关于java - 如何使用 Hibernate4 和 Spring 创建 SessionFactory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30332124/

相关文章:

java - 使用onetomany连接更新实体,而子实体中没有id

java - Tomcat 7 CometProcessor 上缺少 cometd 事件

java - 正则表达式在某些条件下重新匹配字符

Java Swing 组件在第二个屏幕上出现黑色错误

java - 使用 Spring Security 进行 hibernate

spring-boot - Spring Boot 应用程序找不到 SQLite jdbc 驱动程序类

java - Hibernate 4.0 的事务锁定问题

java - 将 JSON 解析为字符串数组或 xml

java - spring boot 中的嵌入式 Tomcat 阻塞了一些关键字

java - 如何在 VS Code 中为 Spring Boot 项目添加 JVM 参数?