为什么我的Hibernate会话总是为空?

时间:2013-03-25 16:19:44

标签: java mysql database hibernate null

我正在使用Hibernate连接到我的数据库,当我想从数据库加载数据时,我会在会话中获得空指针异常。我不知道为什么?一切对我来说都很好:< 我有这个类从db读取:

package bbstats.domain;

import bbstats.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class EventManager extends HibernateUtil
{

    @Autowired
    SessionFactory sessionFactory;

    protected Class<DbUserData> clazz;

    public List<DbUserData> getAll()
    {
        return this.getCurrentSession().createCriteria(clazz).list();
    }

    protected final Session getCurrentSession()
    {
        return this.sessionFactory.getCurrentSession();
    }

    public static void main(String args[])
    {
        EventManager eventManager = new EventManager();
        System.out.println(eventManager.getAll());
    }
}

package bbstats.util;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class HibernateUtil extends HibernateDaoSupport
{
    private SessionFactory sessionFactory;

    @Autowired
    public void anyMethodName(SessionFactory sessionFactory)
    {
        setSessionFactory(sessionFactory);
    }
}

package bbstats.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "Users")
public class DbUserData
{
    @Column(name = "id", unique = true, nullable = false)
    private Long id;
    @Column(name = "nick", nullable = false, length = 26)
    private String title;

    public DbUserData() {}

    public Long getId() {
        return id;
    }

    private void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

当我尝试运行它时,我得到了异常:

Exception in thread "main" java.lang.NullPointerException
    at bbstats.domain.EventManager.getCurrentSession(EventManager.java:25)

就在这里:

protected final Session getCurrentSession()
{
    return this.sessionFactory.getCurrentSession();
}

为什么呢?我该如何解决这个问题?

编辑: 我有这个标签的文件 这是对的吗?我没有带标签的其他文件

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:utils="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

    <!-- Hibernate session factory -->
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <property name="packagesToScan" ref="sessionFactoryDomainToScan"/>

    </bean>

    <utils:list id="sessionFactoryDomainToScan">
        <value>bbstats.domain</value>
    </utils:list>


    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties" ref="clientProperties"/>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
    </bean>


    <bean id="clientProperties"
          class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations" value="/database.properties"/>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

    </bean>
</beans>

还是应该为我的EventManager类添加一些其他bean? 可能是不需要一些豆子吗?

依赖关系:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.2.1.RELEASE</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.1.9.Final</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-annotations</artifactId>
        <version>3.5.6-Final</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>net.sourceforge.jtds</groupId>
        <artifactId>jtds</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.0.3.RELEASE</version>
    </dependency>

现在异常: Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'eventManager' defined in class path resource [hibernate.cfg.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [hibernate.cfg.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition; Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [hibernate.cfg.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/cache/CacheProvider

3 个答案:

答案 0 :(得分:1)

为了注入SessionFactory(感谢注释@Autowired),bean EventManager必须由容器(即Spring)和自己实例化(正如您在主要方法中所做的那样:EventManager eventManager = new EventManager();

答案 1 :(得分:1)

您应该从spring上下文中检索EventManager实例。

您可以将eventManager定义为文件中的bean。您可以将其定义为:

<bean id="eventManager" class="bbstats.domain.EventManager">
 <property name="sessionFactory" ref="sessionFactory"/>
</bean>

假设您的spring配置文件名是springConfig.xml,而eventManager被定义为bean,那么您可以使用

ApplicationContext context = 
          new ClassPathXmlApplicationContext(new String[] {"springConfig.xml"});

        EventManager eventManager = (EventManager)context.getBean("eventManager");

答案 2 :(得分:0)

删除此方法:

 @Autowired
    public void anyMethodName(SessionFactory sessionFactory)
    {
        setSessionFactory(sessionFactory);
    }

并将@Autowired注释添加到setSessionFactory方法。

<强>更新

sea this links(这里你可以找到解决方案):

  1. first
  2. second
  3. therd