Hibernate 4数据未保存

时间:2013-08-01 21:52:15

标签: java spring hibernate

我做了很多研究,但我没有在这里得到解决方案,我的错误是

org.hibernate.HibernateException: No Session found for current thread
    at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:978)
    at dao.GenericDaoImpl.save(GenericDaoImpl.java:42)
    at dao.UserDao.save(UserDao.java:18)
    at controllers.UserController.userRegistrationSubmit(UserController.java:36)
    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.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

我的SpringConfig文件是

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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-2.5.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">


<context:component-scan base-package="controllers,dao" />
<tx:annotation-driven transaction-manager="transactionManager"/>



  <!-- 
     <tx:advice id="txAdvice" transaction-manager="transactionManager">  
        <tx:attributes>  
            <tx:method name="*"  />  
        </tx:attributes>  
    </tx:advice>     -->

 <bean id="viewResolver"
           class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
           <property name="prefix">
              <value>/WEB-INF/pages/</value>
           </property>
           <property name="suffix">
              <value>.jsp</value>
           </property>
     </bean>

 <bean
    id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

    <property name="configLocation">    
        <value>
            classpath:hibernate.cfg.xml
        </value>
    </property>

    <property name="dataSource" ref="dataSource" />
    <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
                <prop key="hibernate.show_sql">true</prop>
                <!-- <prop key="hibernate.c3p0.min_size">5</prop>
                <prop key="hibernate.c3p0.max_size">20</prop>
                <prop key="hibernate.c3p0.timeout">300</prop>
                <prop key="hibernate.c3p0.max_statements">50</prop>
                <prop key="hibernate.c3p0.idle_test_period">3000</prop>  -->
            </props>
     </property>
</bean>    

<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/foodcartdb" />
    <property name="username" value="root" />
    <property name="password" value="root" />

</bean>

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

</beans>

这是我保存数据的代码

package dao;


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.context.annotation.Configuration;
//import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class GenericDaoImpl<T> implements GenericDao<T> {

    /*public GenericDaoImpl(){
        //Do Also Nothing here ha ha ha
    }
    //@Autowired
    public GenericDaoImpl(SessionFactory sessionFactory){
        super.setSessionFactory(sessionFactory);
    }*/
    /*@Autowired
    protected void init(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }*/

    @Autowired
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;

    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }
    @Override
    public void save(T t) {
        // TODO Auto-generated method stub
        //getHibernateTemplate().save(t);
        this.sessionFactory.getCurrentSession().save(t);
    }

    @Override
    public void update(T t) {
        // TODO Auto-generated method stub
        //getHibernateTemplate().update(t);
        getSession().update(t);
    }

    @Override
    public void delete(T t) {
        // TODO Auto-generated method stub
        //getHibernateTemplate().delete(t);
        getSession().delete(t);
    }

}

请有人帮助我摆脱错误的地方,我花了差不多半天的时间。

3 个答案:

答案 0 :(得分:1)

尝试使用@Repository注释而不是@Configuration@EnableTransactionManagement ...

@Repository
public class GenericDaoImpl<T> implements GenericDao<T> {
    // code goes here
}

@Repository API DOCS here

  

在Spring 2.0及更高版本中,@ Repository注释是一个标记   任何履行角色或刻板印象的类(也称为数据   存储库的Access Object或DAO)。这个标记的用途之一   是例外的自动翻译。

Spring documentation here

答案 1 :(得分:1)

首先,@Configuration类上的组合@EnableTransactionManagementGenericDaoImpl注释是多余的,因为您已经在Spring XML配置文件中启用了注释驱动的事务管理。

其次,GenericDaoImpl应注明为@Repository

第三,您没有发布UserDao课程。它是否继承GenericDaoImpl?如果是这样,请考虑制作GenericDaoImpl抽象类(然后唯一的@Repository应该只有UserDao。)

第四,要获得会话,您必须将方法注释为@Transactional或使用sessionFactory.openSession()。使用@Transactional,Spring可以处理处理打开/关闭会话的样板代码,但会强制您为方法的整个范围创建一个当前的单个事务。为自己打开一个会话可以更好地控制会话管理,但是非常繁琐。

第五,如果UserDao继承GenericDaoImpl,则使用@Transactional方法上的save是没用的,因为(默认情况下)此类注释仅适用于通过bean的接口执行的方法调用。因为在这里使用继承是一种不好的做法,所以你应该删除它并在session.save(t)内部调用UserDao

最后和最不重要,作为旁注,最好使用javax.inject注释进行依赖注入,例如@Inject@Named(替换@Autowire和{{ 1}}分别)。

答案 2 :(得分:0)

我认为您应该在DAO类上使用@Transactional,在单个配置类上使用@Configuration / @EnableTransactionManagement,而不是在每个DAO上使用。