当前位置: 首页 > 知识库问答 >
问题:

Spring 4 Hibernate 4:sessionFactory为空

韦阳辉
2023-03-14

我使用Spring 4.1.6.RELEASE Hibernate 4.3.8.Final。在Tomcat 7上配置并启动web应用程序后,我的sessionFactory==null。

你能写出我做错了什么吗?以下是我的消息来源:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <groupId>org.foxrestful</groupId>
    <artifactId>foxrestful</artifactId>
    <modelVersion>4.0.0</modelVersion>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <jdk.version>1.7</jdk.version>

        <mysql-connector-java.version>5.1.34</mysql-connector-java.version>
        <hibernate.version>4.3.8.Final</hibernate.version>
        <servlet-api.version>3.1.0</servlet-api.version>
        <tomcat.version>2.2</tomcat.version>
        <jersey-libs.version>1.19</jersey-libs.version>
        <spring.version>4.1.6.RELEASE</spring.version>

        <maven-idea-plugin.version>2.2.1</maven-idea-plugin.version>
        <maven-compiler-plugin.version>2.3.2</maven-compiler-plugin.version>
        <maven-war-plugin.version>2.6</maven-war-plugin.version>
    </properties>
    <build>
        <finalName>foxrestful</finalName>
        <resources>
            <resource>
                <filtering>true</filtering>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <!-- Idea Project -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-idea-plugin</artifactId>
                <version>${maven-idea-plugin.version}</version>
            </plugin>

            <!-- Set JDK Compiler Level -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>

            <!-- For Maven Tomcat Plugin -->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>${tomcat.version}</version>
                <configuration>
                    <url>http://localhost:8080/manager/text</url>
                    <server>MyTomcat</server>
                    <path>/foxrestful</path>
                </configuration>
            </plugin>

            <!-- For Web Xml Plugin -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>${maven-war-plugin.version}</version>
                <configuration>
                    <failOnMissingWebXml>true</failOnMissingWebXml>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet-api.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector-java.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey-libs.version}</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>${jersey-libs.version}</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>${jersey-libs.version}</version>
        </dependency>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>


    </dependencies>
</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>fox-rest-servlet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>org.foxresult.resources</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>fox-rest-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring.xml
        </param-value>
    </context-param>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

spring.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: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-4.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:annotation-config />
    <context:component-scan base-package="org.foxresult" />

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

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>org.foxresult.entity.Department</value>
                <value>org.foxresult.entity.Employee</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="cache.provider_class">org.hibernate.cache.internal.NoCachingRegionFactory</prop>
                <prop key="hibernate.cache.default_cache_concurrency_strategy">transactional</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hbm2ddl.auto">create</prop>
            </props>
        </property>
    </bean>

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

    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

这是我的DAO层。我为CRUD操作和具有特定方法的子类创建基本抽象类Abstract道。

AbstractDao.java

package org.foxresult.dao.abstraction;

import org.foxresult.dao.interfaces.GenericDao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;


public abstract class AbstractDao<T, PK extends Serializable> implements GenericDao<T, PK> {

    @Autowired
    protected SessionFactory sessionFactory;

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

    public T getByPK(PK key) {
        T entry = null;
        Session session = null;
        if (key != null)
            try {
                session = sessionFactory.openSession();
                session.clear();
                entry = (T) session.get(getClassType(), key);
            } catch (Exception sql) {
                sql.printStackTrace();
            } finally {
                closeSession(session);
            }
        return entry;
    }

    public List<T> getAll() {
        List<T> result = null;
        Session session = null;
        try {
            session = sessionFactory.openSession();
            session.clear();
            result = session.createCriteria(getClassType()).
                        addOrder(Order.asc("id")).list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeSession(session);
        }
        return result;
    }


    protected void closeSession(Session session) {
        if ((session != null) && (session.isOpen())) {
            session.close();
        }
    }
}

冬眠部道.java

package org.foxresult.dao.implementations;

import org.foxresult.dao.abstraction.AbstractDao;
import org.foxresult.dao.interfaces.DepartmentDao;
import org.foxresult.entity.Department;

@Component
public class HibernateDepartmentDao extends AbstractDao<Department, Integer> implements DepartmentDao {

    public Class<Department> getClassType() {
        return Department.class;
    }

    public Integer getPK(Department object) {
        return object.getId();
    }
}

希望你能帮助我。我是Spring初学者。谢谢

编辑:添加Tomcat日志。当加载webapp时,我向调用getAll方法的服务发送GET请求,并获取sessionFactory的NullPointerExeption。

апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/7.0.59
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          Jan 28 2015 15:51:10 UTC
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         7.0.59.0
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 8.1
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            6.3
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:\Program Files\Java\jdk1.7.0_71\jre
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.7.0_71-b14
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         C:\Users\Andrey\.IntelliJIdea14\system\tomcat\Unnamed_JerseyRESTful_2
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         e:\Compilers\Tools\tomcat\apache-tomcat-7.0.59
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcom.sun.management.jmxremote=
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcom.sun.management.jmxremote.port=1099
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcom.sun.management.jmxremote.ssl=false
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcom.sun.management.jmxremote.authenticate=false
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.rmi.server.hostname=127.0.0.1
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.util.logging.config.file=C:\Users\Andrey\.IntelliJIdea14\system\tomcat\Unnamed_JerseyRESTful_2\conf\logging.properties
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=e:\Compilers\Tools\tomcat\apache-tomcat-7.0.59\endorsed
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\Andrey\.IntelliJIdea14\system\tomcat\Unnamed_JerseyRESTful_2
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=e:\Compilers\Tools\tomcat\apache-tomcat-7.0.59
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.io.tmpdir=e:\Compilers\Tools\tomcat\apache-tomcat-7.0.59\temp
апр 06, 2015 5:13:54 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: Loaded APR based Apache Tomcat Native library 1.1.32 using APR version 1.5.1.
апр 06, 2015 5:13:54 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
апр 06, 2015 5:13:54 PM org.apache.catalina.core.AprLifecycleListener initializeSSL
INFO: OpenSSL successfully initialized (OpenSSL 1.0.1j 15 Oct 2014)
апр 06, 2015 5:13:54 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-apr-8080"]
апр 06, 2015 5:13:54 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-apr-8009"]
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1056 ms
апр 06, 2015 5:13:54 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
апр 06, 2015 5:13:54 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.59
апр 06, 2015 5:13:54 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-apr-8080"]
апр 06, 2015 5:13:54 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-apr-8009"]
апр 06, 2015 5:13:54 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 54 ms
Connected to server
[2015-04-06 05:13:55,424] Artifact JerseyRESTful:war: Artifact is being deployed, please wait...
апр 06, 2015 5:13:55 PM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(e:\Compilers\Tools\tomcat\apache-tomcat-7.0.59\webapps\foxrestful\WEB-INF\lib\javax.servlet-api-3.1.0.jar) - jar not loaded. See Servlet Spec 3.0, section 10.7.2. Offending class: javax/servlet/Servlet.class
апр 06, 2015 5:13:55 PM org.apache.catalina.deploy.WebXml setVersion
WARNING: Unknown version string [3.1]. Default version will be used.
апр 06, 2015 5:13:57 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
апр 06, 2015 5:13:57 PM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Mon Apr 06 17:13:57 FET 2015]; root of context hierarchy
апр 06, 2015 5:13:57 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/spring.xml]
апр 06, 2015 5:13:58 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
апр 06, 2015 5:13:58 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
апр 06, 2015 5:13:58 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.8.Final}
апр 06, 2015 5:13:58 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
апр 06, 2015 5:13:58 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
апр 06, 2015 5:13:58 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
апр 06, 2015 5:13:58 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
апр 06, 2015 5:13:58 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
апр 06, 2015 5:13:59 PM org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@3f8f29d1] of Hibernate SessionFactory for HibernateTransactionManager
апр 06, 2015 5:13:59 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 1734 ms
апр 06, 2015 5:13:59 PM com.sun.jersey.api.core.PackagesResourceConfig init
INFO: Scanning for root resource and provider classes in the packages:
  org.foxresult.resources
апр 06, 2015 5:13:59 PM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
  class org.foxresult.resources.EmployeeResource
  class org.foxresult.resources.DepartmentResource
апр 06, 2015 5:13:59 PM com.sun.jersey.api.core.ScanningResourceConfig init
INFO: No provider classes found.
апр 06, 2015 5:13:59 PM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.19 02/11/2015 03:25 AM'
[2015-04-06 05:14:00,044] Artifact JerseyRESTful:war: Artifact is deployed successfully
[2015-04-06 05:14:00,045] Artifact JerseyRESTful:war: Deploy took 4 621 milliseconds
java.lang.NullPointerException
    at org.foxresult.dao.abstraction.AbstractDao.getAll(AbstractDao.java:99)
    at org.foxresult.resources.DepartmentResource.getAll(DepartmentResource.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2466)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2455)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

编辑(2):添加DepartmentResource.java.这是一个泽西REST服务。

package org.foxresult.resources;

import org.foxresult.dao.implementations.HibernateDaoFactory;
import org.foxresult.entity.Department;
import org.foxresult.entity.wrapper.DepartmentWrapper;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;

@Path("/departments")
public class DepartmentResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<DepartmentWrapper> getAll() {
        return wrap(HibernateDaoFactory.getDepartmentDao().getAll());
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{id}")
    public DepartmentWrapper get(@PathParam("id") int id) {
        return wrap(HibernateDaoFactory.getDepartmentDao().getByPK(id));
    }
}

共有2个答案

宦源
2023-03-14

您的配置似乎是正确的。你能尝试以下步骤吗

>

  • 在事务管理器中也添加对数据源的引用
    <代码>

    将HibernateDepartmentDao的注释从@Component更改为@Repository

  • 朱淮晨
    2023-03-14

    更新我的答案:

    1. 网络.xml应该使用具有“Spring”功能的Jersey Servlet。

    在 Web .xml中,更改

     <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    
      To This:
    
     <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
    

    所以,在pom中.xml添加如下内容:

    <dependency>
                <groupId>com.sun.jersey.contribs</groupId>
                <artifactId>jersey-spring</artifactId>
                <version>1.8</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-aop</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-core</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-web</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-beans</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-context</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    

    使DepartmentResource具有@Component注释。

    这对Spring不起作用:< code > public static DepartmentDao getDepartmentDao(){ return new HibernateDepartmentDao();}

    你必须让Spring给你道。

    @Autowired
    HibernateDepartmentDao hibernateDepartmentDao;
    
     类似资料:
    • 我在尝试将Spring与Hibernate集成时遇到了一些问题。从日志中,表和数据库似乎已经创建,但我找不到数据库文件,在检查sessionFactory时,我得到了nullpointer异常,我无法真正理解发生了什么。 以下是我的配置文件: null 编辑:这是UtenteDaoImpl类,它不做任何事情,因为它继承了BaseDao的东西。

    • 问题内容: 也许有人可以解释使用哪个?什么时候,为什么? 问题答案: HibernateTemplate的Javadoc说: 注意:从Hibernate 3.0.1开始,事务性Hibernate访问代码也可以采用普通的Hibernate样式进行编码。因此,对于新启动的项目,请考虑采用基于SessionFactory.getCurrentSession()的标准Hibernate3样式编码数据访问对

    • 问题内容: 如何使用Java配置创建SessionFactory? 由于某些原因,此方法不起作用…它总是返回null。 问题答案: 这里值得一提的是Spring 3.1引入了LocalSessionFactoryBuilder,它专门设计用于@Bean方法中。 http://static.springsource.org/spring/docs/3.1.0.RC1/javadoc- api/org

    • 问题内容: 我一直在解决这个问题,而 Hibernate SessionFactory 和 JPA EntityManagerFactory的 区别在于JPA是标准的。您可以使用它而不必担心底层的ORM。但它在后台调用了底层的sessionFactory(如果我错了,请纠正我) 但是,如果有人知道他将来必须坚持使用hibernate作为ORM,那么他应该从这两个 工厂中 选择什么,为什么? 其次,

    • 问题内容: 我有一个Spring + Hibernate / Flex应用程序,需要在数据库模式之间动态切换。为了实现这个目标我实现了一个AbstractRoutingDataSource下面这个文章。不幸的是,它不起作用。它实际上以默认架构(logical_public)执行SQL。任何帮助将不胜感激。谢谢。 这是我的设置: applicationContext.xml 包含两个数据源。每个数据

    • 应用Context.ml 包it.davidefruci.casadiscografica2.dao 把它打包。davidefruci。卡萨迪斯科格拉菲卡2。daoImpl; Tomcat没有部署应用程序。上面说 FAIL-在上下文路径 /CasaDiscografica2部署应用程序,但上下文无法启动 给我一个错误: 组织。springframework。豆。工厂BeanCreationExce