嵌套异常是java.lang.NoSuchMethodError:org.hibernate.SessionFactory.openSession()Lorg / hibernate / classic / Session;]

时间:2015-12-17 05:48:33

标签: spring hibernate spring-mvc spring-4 hibernate-4.x

我正在使用Spring 4.x和Hibernate 4.x来开发简单的基于休息的CURD操作。每当我调用url获取数据库中的所有用户时,我都会遇到异常。

    for servlet [helloApp] in context with path [/helloApp] threw exception [Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session;] with root cause
java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session;
    at org.springframework.orm.hibernate3.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:496)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:420)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:257)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy27.getAllPerson(Unknown Source)
    at com.controller.PersonController.getAllPerson(PersonController.java:30)
    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.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:748)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807)
    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.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    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:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    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:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

以下是helloApp-servlet.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" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

   <mvc:annotation-driven/> 
   <context:annotation-config/>
   <context:component-scan base-package="com"/>
   <import resource="db-config.xml" />   

   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/" />
      <property name="suffix" value=".jsp" />
   </bean>  
</beans>

以下是db-config.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" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
    <bean id="dbPropertyConfigurer"
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>/WEB-INF/db_config.properties</value>
            </list>
        </property>
    </bean>
    <!-- Database Properties -->
    <bean id="dataSource"
        class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
                p:driverClass="${jdbc.driver.className}"
                p:jdbcUrl="${jdbc.url}"
                p:user="${jdbc.username}"
                p:password="${jdbc.password}"               
                />
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
            <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hbm2ddl.auto">update</prop>
            </props>
        </property>
        <property name="packagesToScan" value="com.entity" />
    </bean>
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

任何人都可以帮助您删除此例外。我正在使用邮递员进行所有剩余的凝乳操作。如果需要任何其他代码,请告诉我。

请在下面找到控制器 -

package com.controller;

import java.util.List;
import java.util.Date;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;


import com.dao.PersonDAO;
import com.entity.Person;

@RestController
public class PersonController {
    private static Logger logger = Logger.getLogger(PersonController.class);

    @Autowired PersonDAO personDAO;


     @RequestMapping(value="/person/all",method = RequestMethod.GET,headers="Accept=application/json")
     public List<Person> getAllPerson(){
         List<Person> persons=personDAO.getAllPerson();
         logger.info("## Returninf the persons !!!"+persons);
         return persons;
     }

     @RequestMapping(value="/person/{personId}",method = RequestMethod.GET,headers="Accept=application/json")
     public Person getOnePerson(@PathVariable int personId){
         Person person=personDAO.getPerson(personId);
         logger.info("## Returning the person with personId..."+personId);
         return person;
     }


     @RequestMapping(value="/person/create",method = RequestMethod.POST,headers="Accept=application/json")
     public List<Person> createNewPerson(@RequestBody Person person){
         Person persons=null;
         persons.setName(person.getName());
         persons.setLast_accessed(new Date());
         logger.error("## Inside person creation controller !!!!!!");

         try{
             personDAO.createPerson(persons);
             logger.info("####### Creating persons !!!!!");
         }catch(Exception e){
             logger.error("$$$ Exception occured in creating person!!!!");
             e.printStackTrace();
         }
         return getAllPerson();
     }

     @RequestMapping(value="/person/delete/{personId}",method = RequestMethod.POST,headers="Accept=application/json")
     public List<Person> deletePerson(@PathVariable int personId){
            personDAO.deletePerson(personId);   
            logger.info("## Successfully deleted the person with personId "+personId);
         return getAllPerson();
     }

     @RequestMapping(value="/person/update",method = RequestMethod.POST,headers="Accept=application/json")
     public List<Person> updatePerson(@RequestBody Person person){
         Person persons=personDAO.getPerson(person.getId());
         persons.setName(person.getName());
         persons.setLast_accessed(new Date());
         try{
             personDAO.updatePerson(persons);
             logger.info("Updating person !!!!!");
         }catch(Exception e){
            logger.error("Error in updating person !!!!!!");
             e.printStackTrace();
         }
         return getAllPerson();
     }
}

具有会话工厂对象的DAO类 -

package com.dao;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.apache.log4j.Logger;
import com.entity.Person;

@Component
@Transactional(readOnly=true)
public class PersonDAOImpl implements PersonDAO {
    private static Logger logger = Logger.getLogger(PersonDAOImpl.class);

    @Autowired
    private SessionFactory sessionFactory;
    Session session = null;

    private void assignSessionLocalVariable(){
        if(session == null || !session.isOpen()){
            try{                
                session = sessionFactory.openSession();
            }catch(Exception e){session = null;
                logger.error("/### Session is null ####/");
            }
        }
    }


    @Override
    public List<Person> getAllPerson() {
        List<Person> persons=null;
        assignSessionLocalVariable();
        if(session!=null){
            try{    
                    String q="from person ";
                    Query query = session.createQuery(q);
                    persons = query.list(); 
            }catch(Exception e){

                logger.error("########### Exception occured while fetching all persons in IMPL ########## ["+e+"]\n ");
            }
        }   
        return persons;
    }

    @Override
    public Person getPerson(int personId) {
        assignSessionLocalVariable();
        Person person= (Person) session.load(Person.class, personId);
        session.close();
        return person;
    }

    @Override
    public void createPerson(Person person) {
        assignSessionLocalVariable();
        try{
            Transaction tx=session.beginTransaction();
            session.save(person);
            tx.commit();
        }catch(Exception e){
            e.printStackTrace();
        }
        session.close();
    }

    @Override
    public void deletePerson(int personId) {
        assignSessionLocalVariable();
        Person person= (Person) session.load(Person.class, personId);
        try{
            session.delete(person);
        }catch(Exception e){
            e.printStackTrace();
        }
        session.close();

    }

    @Override
    public void updatePerson(Person person) {
        assignSessionLocalVariable();
        try{
                Transaction tx=session.beginTransaction();
                session.update(person);
                tx.commit();
        }catch(Exception e){
                logger.error("### Exception occured while updating PERSON #### in IMLP ["+e+"] \n");
        }
        session.close();

    }

}

1 个答案:

答案 0 :(得分:1)

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

您的TransactionManager配置错误,配置Hibernate4事务管理器bean而不是Hibernate3。并确保你的依赖是正确的。