0

我在一个简单的java应用程序中使用带有spring 3.1的Hibernate 4。

我使用以下代码创建 Spring SessionFactory,然后将其转换为休眠 SessionFactory:请这里缺少 waht ...这是正确的方法吗?还是我错过了什么..?请帮忙!

.....
......
context=new ClassPathXmlApplicationContext(new String[]{"spring.xml"});
    return (SessionFactory) context.getBean("mySessionFactory");
......

会话工厂的 CurrentSessionContext 始终为空!所以我无法执行

sessionFactory.getcurrentSession() 

-> 给我一个 java.lang.NullPointer 异常

spring.xml 中的 myBean 声明:

<?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.1.xsd">



 <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/test"/>
    <property name="username" value="root"/>
    <property name="password" value=""/>
  </bean>

      <bean id="mySessionFactory"  name="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" scope="singleton">
        <property name="dataSource" ref="myDataSource"/>
        <property name="mappingResources">

          <list>
            <value>TblUrls.hbm.xml</value>
          </list>
        </property>
         <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> 
                <prop key="hibernate.show_sql">true</prop> 
                <prop key="hibernate.transaction.jta.platform">org.hibernate.service.jta.platform.internal.SunOneJtaPlatform</prop>
                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
              </props>
        </property>
      </bean>
   <bean class="org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor">
        <property name="sessionFactory">
            <ref local="mySessionFactory" />
        </property>
    </bean>

    <bean id = "transactionManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name = "sessionFactory" ref = "mySessionFactory" />

    </bean>
<!--   <bean id="myProductDao" class="hib.TblUrlsHome"> -->
<!--     <property name="sessionFactory" ref="mySessionFactory"/> -->
<!--   </bean> -->

</beans>
4

1 回答 1

0

你所要做的
sessionFactory.openSession();

这应该可以解决您的问题。

于 2013-06-25T09:35:48.453 回答