0

我认为我的配置确实有问题。这就是问题所在。我可以这样打开会话:

    @Test
    public void testSessionFactory()
    {
        try {
            Configuration configuration = new Configuration()
            .addClass(com.mcfly.songme.pojo.Sysparameters.class)
            .configure();
            ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder().applySettings(configuration
                    .getProperties());

            SessionFactory sessionFactory = configuration
                    .buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry());
            System.out.println("test");
            Session session = sessionFactory.openSession();
            System.out.println("Test connection with the database created successfuly.");
        }catch (Throwable ex) { 
            ex.printStackTrace();
            throw new ExceptionInInitializerError(ex);
        }
    }

但是,如果我这样做,则会话永远不会打开:

    @Test
public void testFindAll() 
{
    try {
        List<Sysparameters> sys = null;
        System.out.println("test");
        SysparametersDAO sysDao = new SysparametersDAO();
        System.out.println("test");
        sys = sysDao.findAll();
        System.out.println(sys.size());
    } catch (Throwable ex) { 
        ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }
}

我的 configuration.xml :

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

    <context:annotation-config/>

    <context:component-scan base-package="com.mcfly.songme.pojo" />


    <!-- JDBC data source -->
<!--      <bean id="myDataSource" class="org.springframework.jdb.datasource.DriverManagerDataSource"> -->
    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/songme"/>
        <property name="maxActive" value="10"/> 
        <property name="minIdle" value="5"/> 
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        <property name="validationQuery" value="SELECT 1"/>
    </bean>

    <!-- hibernate session factory  -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="packagesToScan" value="com.mcfly.songme.pojo"/>
        <property name="configLocation" value="classpath:com/mcfly/songme/pojo/hibernate.cfg.xml" />
    </bean> 

    <!-- Hibernate transaction Manager -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!--     Activates annotation based transaction management -->
    <tx:annotation-driven transaction-manager="transactionManager"/>


</beans>

我的 dao 文件:

package com.mcfly.songme.pojo;

import java.io.File;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Component
public class SysparametersDAO 
{
    @Autowired(required=true)
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;

    private  Session session = sessionFactory.getCurrentSession();


    @Transactional
    public List<Sysparameters> findAll() 
    {
        try {
            if(getSessionFactory()==null) {
                System.out.println("NULL SESSION FACTORY");
            }
            session = getSessionFactory().getCurrentSession();
        } catch (Exception e) {
            e.printStackTrace();
        }
        @SuppressWarnings("unchecked")
        List<Sysparameters> sys = (List<Sysparameters>) session.createQuery("from sysparameters").list();
        return sys;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

}

我的实体文件:

package com.mcfly.songme.pojo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

// Generated 8 oct. 2013 16:31:22 by Hibernate Tools 4.0.0

/**
 * Sysparameters generated by hbm2java
 */
@Entity
@Table(name = "sysparameters")
public class Sysparameters implements java.io.Serializable {

    @Id
    private Integer id;
    @Column(name = "name")
    private String name;
    @Column(name = "value")
    private String value;

    public Sysparameters() {
    }

    public Sysparameters(String name, String value) {
        this.name = name;
        this.value = value;
    }

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return this.value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}

我的测试文件配置:

package com.mcfly.songme.pojo.test;

@ContextConfiguration("classpath:/files-servlet.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class SysparameterPOJOTest 
{

我真的不明白我做错了什么。如果您有想法,请寻求帮助。


仍然有一个会话工厂 null

oct. 09, 2013 11:38:06 AM org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.apache.commons.dbcp.BasicDataSource@102674b7] of Hibernate SessionFactory for HibernateTransactionManager
java.lang.NullPointerException
    at com.mcfly.songme.pojo.test.SysparameterPOJOTest.testFindAll_(SysparameterPOJOTest.java:81)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)

像你说的那样,我试图让会话脱离对象

    @Test
    public void testFindAll_() 
    {
        Session session = null;
        try {
            Sysparameters sys = null;
            SysparametersDAO sysDAO = new SysparametersDAO();
            session = sysDAO.getSessionFactory().getCurrentSession();
//          sys = new SysparametersHome().findById(1);
        } catch (Throwable ex) { 
            ex.printStackTrace();
            throw new ExceptionInInitializerError(ex);
        } finally {
            Assert.assertNotNull(session);
        }
    }

所以我的会话工厂似乎仍然为空:/

4

1 回答 1

0

第一个问题是这个

@Autowired(required=true)
@Qualifier("sessionFactory")
private SessionFactory sessionFactory;

private Session session = sessionFactory.getCurrentSession();

Spring 自动装配分两步进行:首先实例化您的 bean(在这种情况下调用默认构造函数),然后使用反射设置字段。在上面的例子中,当创建对象时,字段也被初始化,默认为null. 所以当

private Session session = sessionFactory.getCurrentSession();

尝试获取Session它调用getCurrentSession()null引用。

您不应该Session在实例级别获取对象。您应该在每个单独的方法调用中获取它。

于 2013-10-08T15:32:24.050 回答