hibernate会话工厂创建中的空指针异常

时间:2016-01-31 13:14:28

标签: java hibernate maven

我是java的新手,想要使用hibernate,但我收到了以下错误:

TEstting
Jan 31, 2016 6:36:43 PM org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.2.1
Jan 31, 2016 6:36:43 PM org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
Jan 31, 2016 6:36:43 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
Jan 31, 2016 6:36:43 PM org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
Jan 31, 2016 6:36:43 PM org.hibernate.cfg.Configuration configure
INFO: configuring from resource: hibernate.cfg.xml
Jan 31, 2016 6:36:43 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: hibernate.cfg.xml
Jan 31, 2016 6:36:43 PM org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : pojo.Contractor_Schedule__c
java.lang.NullPointerException
    at org.apache.catalina.loader.WebappClassLoaderBase.findLoadedResource(WebappClassLoaderBase.java:3558)
    at org.apache.catalina.loader.WebappClassLoaderBase.getResourceAsStream(WebappClassLoaderBase.java:1633)
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:557)
    at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1584)
    at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1552)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1531)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1505)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
    at Utility.HibernateUtility.<clinit>(HibernateUtility.java:15)
    at services.AccountServices.createAccount(AccountServices.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
    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.RightHandPathRule.accept(RightHandPathRule.java:147)
    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:731)
    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 services.JaxRsFilterAuthentication.doFilter(JaxRsFilterAuthentication.java:31)
    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:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Initial SessionFactory creation failed.java.lang.NullPointerException

下面是我的hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory name="scrubbi">
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.password">aQGwrzids5kF</property>
  <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/scrubbi</property>
  <property name="hibernate.connection.username">admin8KJpCbh</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.archive.autodetection">class</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <property name="hibernate.format_sql">true</property>
  <property name="hibernate.show_sql">true</property>
  <mapping resource="pojo.Contractor_Schedule__c"/>
 </session-factory>
</hibernate-configuration>

下面是我的HibernateUtility类

package Utility;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class HibernateUtility {

    private static final SessionFactory sessionFactory;

    static {
            System.out.println("TEstting");
        try {

            sessionFactory = new Configuration().configure("hibernate.cfg.xml")
            .buildSessionFactory();

        } catch (Throwable ex) {
            ex.printStackTrace();
            System.err.println("Initial SessionFactory creation failed." + ex);

            throw new ExceptionInInitializerError(ex);

        }

    }

    public static SessionFactory getSessionFactory() {

        return sessionFactory;

    }
}

下面是我的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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>scrubbi</groupId>
    <artifactId>scrubbi</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>scrubbi</name>
    <repositories>
        <repository>
            <!-- The JBoss Public repository is a composite repository of several 
                major repositories. See http://community.jboss.org/wiki/MavenGettingStarted-Users -->
            <id>jcentral</id>
            <url>https://repo1.maven.org/maven2/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <!-- You can disable snapshot resolution to speed up your builds -->
            <snapshots>
                <enabled>false</enabled>
            </snapshots> 
        </repository>
    </repositories>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.6</maven.compiler.source>
        <maven.compiler.target>1.6</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.0.Final</version> 
        </dependency>

        <dependency> 
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.5.6-Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>3.3.0.ga</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId> 
            <artifactId>slf4j-api</artifactId>
            <version>1.5.5</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId> 
            <version>3.3.0.Final</version>
        </dependency>


        <dependency> 
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.2-1003-jdbc4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.25</version>
        </dependency>     
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.19</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.19</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>1.19</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>1.19</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>1.19</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
           <groupId>com.owlike</groupId>
           <artifactId>genson</artifactId>
           <version>1.3</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>                       
    </dependencies>
    <profiles>
        <profile>
            <!-- When built in OpenShift the 'openshift' profile will be used when 
                invoking mvn. -->
            <!-- Use this profile for any OpenShift specific customization your app 
                will need. -->
            <!-- By default that is to put the resulting archive into the 'webapps' 
                folder. -->
            <!-- http://maven.apache.org/guides/mini/guide-building-for-different-environments.html -->
            <id>openshift</id>
            <build>
                <finalName>scrubbi</finalName>
                <plugins>
                    <plugin>
                        <artifactId>maven-war-plugin</artifactId>
                        <version>2.1.1</version>
                        <configuration>
                            <outputDirectory>webapps</outputDirectory>
                            <warName>ROOT</warName>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

以下是我调用会话工厂的代码

package services;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.hibernate.Session;
import org.hibernate.Transaction;

import Utility.HibernateUtility;
import pojo.Account;
import pojo.Contractor_Schedule__c;
import pojo.PersonAccount;

@Path("/PersonAccount")
public class AccountServices {

    @Path("/create")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response createAccount(List<PersonAccount> records) throws Exception {

        //throw new WebApplicationException(Response.status(400).entity("This is invalid").build());
        Session session = HibernateUtility.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        for(PersonAccount record : records){
            session.saveOrUpdate(record);
        }
        tx.commit();
        session.close();
        return Response.status(Status.CREATED).entity(records).build();
    }


}

以下是项目结构图像

enter image description here

是否有任何配置问题或者我做错了?

3 个答案:

答案 0 :(得分:1)

使用<mapping class="pojo.Contractor_Schedule__c"/>代替<mapping resource="pojo.Contractor_Schedule__c"/>

<mapping class="Test"/>用于指向带注释的类,而<mapping resource="Test.hbm.xml"/>用于查找映射文件

答案 1 :(得分:1)

您正在使用带注释的类来映射而不是HBM文件。 resources用于那些HBM文件。您需要使用classespackage。这也在the reference guide中解释。

<mapping class="pojo.Contractor_Schedule__c" />

或者使用package自动检测所有课程。

<mapping package="pojo" />

答案 2 :(得分:-2)

hibernate.cfg.xml文件直接放入src文件夹。