无法让HibernateUtil工作

时间:2016-05-01 09:05:01

标签: java hibernate maven

我在运行项目时遇到此错误,无法确定正在进行的操作。

  

java.lang.NoClassDefFoundError:无法初始化类   com.sepa.util.HibernateUtil at   com.sepa.controller.InicioBean.getProvincias(InicioBean.java:27)at at   sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)     在   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     在java.lang.reflect.Method.invoke(Method.java:498)at   javax.el.BeanELResolver.getValue(BeanELResolver.java:363)at at   com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)     在   com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)     在com.sun.el.parser.AstValue.getValue(AstValue.java:140)at   com.sun.el.parser.AstValue.getValue(AstValue.java:204)at at   com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)     在   org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)     在   com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)     在   javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)     在   javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)     在   javax.faces.component.UISelectItem.getItemValue(UISelectItem.java:208)     在   com.sun.faces.renderkit.SelectItemsIterator.initializeItems(SelectItemsIterator.java:197)     在   com.sun.faces.renderkit.SelectItemsIterator.hasNext(SelectItemsIterator.java:135)     在   com.sun.faces.renderkit.html_basic.MenuRenderer.renderOptions(MenuRenderer.java:762)     在   com.sun.faces.renderkit.html_basic.MenuRenderer.renderSelect(MenuRenderer.java:847)     在   com.sun.faces.renderkit.html_basic.MenuRenderer.encodeEnd(MenuRenderer.java:297)     在   javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920)     在javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)     在javax.faces.render.Renderer.encodeChildren(Renderer.java:176)at   javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)     在javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)     在javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)     在javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)     在   com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458)     在   com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)     在   javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)     在   com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)     在com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)at   com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)     在javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)at   org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)     在   org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)     在   org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)     在   org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)     在   org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)     在com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)at   org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)     在   org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)     在   org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)     在   com.sun.enterprise.v3.services.impl.ContainerMapper $ HttpHandlerCallable.call(ContainerMapper.java:459)     在   com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)     在   org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)     在   org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)     在   org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)     在   org.glassfish.grizzly.filterchain.ExecutorResolver $ 9.execute(ExecutorResolver.java:119)     在   org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)     在   org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)     在   org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)     在   org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)     在   org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)     在   org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)     在   org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)     在   org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)     在   org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access $ 100(WorkerThreadIOStrategy.java:56)     在   org.glassfish.grizzly.strategies.WorkerThreadIOStrategy $ WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)     在   org.glassfish.grizzly.threadpool.AbstractThreadPool $ Worker.doWork(AbstractThreadPool.java:591)     在   org.glassfish.grizzly.threadpool.AbstractThreadPool $ Worker.run(AbstractThreadPool.java:571)     在java.lang.Thread.run(Thread.java:745)

这是我的InicioBean类

package com.sepa.controller;

import com.sepa.model.Provincia;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import java.util.List;

import com.sepa.util.HibernateUtil;

import org.hibernate.Session;
import org.hibernate.Query;

@ManagedBean(name = "inicioBean", eager = true)
@RequestScoped
public class InicioBean {

    private Provincia provincia;
    List<Provincia> provincias;
    String algo;

    public List<Provincia> getProvincias() {
        Session session = null;
        provincias = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            Query query = session.createQuery("from Provincia");
            provincias = (List<Provincia>) query.list();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (session != null) {
                session.close();
            }
        }
        return provincias;
    }
}

这是我的HibernateUtil类

package com.sepa.util;

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

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml)
            // config file.
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception.
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

这是我的hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/SEPA</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">sepaweb</property>
        <mapping class="com.sepa.model.Provincia"/>
    </session-factory>
</hibernate-configuration>

这是我的pom

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sepa</groupId>
    <artifactId>SEPAWeb</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>SEPAWeb</name>

    <dependencies>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.faces</artifactId>
            <version>2.2.7</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

我真的不知道发生了什么,我尝试了很多东西,更改了hibernate.cfg.xml的文件夹,尝试了很多HibernateUtil文件但我无法获得这项工作。

Project's structure

感谢!

1 个答案:

答案 0 :(得分:0)

解决了这个问题。 HibernateUtil不正确。 更改为:

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;

public class HibernateUtil {
    private static SessionFactory sessionFactory;

    private static SessionFactory buildSessionFactory() {
        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().
                configure("hibernate.cfg.xml").build();

        Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().
                build();

        SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder();

        SessionFactory sessionFactory = sessionFactoryBuilder.build();

        return sessionFactory;
    }

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            sessionFactory = buildSessionFactory();
        }
        return sessionFactory;
    }
}

如果您正在使用glassfish,则需要在glassfish4 \ glassfish \ modules中粘贴jboss-logging-3.3.0.Final.jar。 (重命名为jboss-logging并替换另一个)