引起原因:JBoss Wildfly和JPA注入中的java.lang.NullPointerException

问题描述 投票:0回答:1

我试图从JPAUtil.class向我的DAO进行我的entityManager的简单注入。当我创建一个实例时,它可以工作,但是当尝试使用@Inject时,我得到一个空指针异常。也许有些简单,但我不明白。

Persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
   http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
    <persistence-unit name="jpa" transaction-type="JTA">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>model.Client</class>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL9Dialect" />
            <property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
            <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/prueba1" />
            <property name="hibernate.connection.username" value="kevinsantiago" />
            <property name="hibernate.connection.password" value="" />
            <!--<property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.flushMode" value="FLUSH_AUTO" />
           <property name="hibernate.hbm2ddl.auto" value="update" />-->
        </properties>
    </persistence-unit>
</persistence>

DAO类

package dao;

import model.Client;
import model.JPAutil;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;

import javax.persistence.Query;

import java.util.List;

/**
 * Diese Class ist die verbindung
 * mit die Data base Erzeugen
 */

public class ClientDAO {
    //HIER WORKS WOTHOUT PROBLEM
    //EntityManager entity = JPAutil.getEntityManeger();
    //HIER DOES NOT WORK
    @Inject
    @Named("Pruebe")
    private EntityManager entity;

    public void create(Client client) {
        entity.getTransaction().begin();
        entity.persist(client);
        entity.getTransaction().commit();

    }

    public void update(Client client) {
        entity.getTransaction().begin();
        entity.merge(client);
        entity.getTransaction().commit();

    }

    public List<Client> findall() {
        Query q = entity.createQuery("SELECT c FROM Client c");
        List<Client> listaC = q.getResultList();
        return listaC;
    }

    public Client findbyId(int idc) {
        Query q = entity.createQuery("SELECT c FROM Client c WHERE id=" + idc);
        Client C  = (Client) q.getSingleResult();
        return C;
    }

    public void remove(int id) {
        Client c = new Client();
        c = entity.find(Client.class, id);
        entity.getTransaction().begin();
        entity.remove(c);
        entity.getTransaction().commit();
    }
}

JPA


import javax.enterprise.inject.Produces;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;


/**
 * Hier ist erzeugt die entitty manager,
 * um in die Dao zu nutzen
 */
public class JPAutil{
    private static final String PUName = "jpa";
    private static EntityManagerFactory factory;

    private static EntityManager em;

    @Produces
    @Named("Pruebe")
    public static EntityManager getEntityManeger() {
        if (factory == null) {
            factory = Persistence.createEntityManagerFactory(PUName);
            em = factory.createEntityManager();
        }
        return em;
    }

    public static EntityManagerFactory getEntityManegerFactory() {
        if (factory == null) {
            factory = Persistence.createEntityManagerFactory(PUName);
        }
        return factory;
    }

    public static void shutDown() {
        if (factory != null) {
            factory.close();
        }
    }


}

现在只是想复制错误

Context Path:/JSFJPA_HelloWorld_war_exploded
Servlet Path:/index.xhtml
Path Info:null
Query String:null
Stack Trace:
javax.servlet.ServletException
    at [email protected]//javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:725)
    at [email protected]//javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)
    at [email protected]//io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
    at [email protected]//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
    at io.opentracing.contrib.opentracing-jaxrs2//io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter.doFilter(SpanFinishingFilter.java:52)
    at [email protected]//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    at [email protected]//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    at [email protected]//io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
    at [email protected]//io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at [email protected]//io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
    at [email protected]//io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at [email protected]//org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at [email protected]//io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
    at [email protected]//io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
    at [email protected]//io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at [email protected]//io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at [email protected]//io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at [email protected]//io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at [email protected]//io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at [email protected]//io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at [email protected]//io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at [email protected]//org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at [email protected]//org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
    at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:269)
    at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:78)
    at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:133)
    at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:130)
    at [email protected]//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at [email protected]//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at [email protected]//org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
    at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:249)
    at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:78)
    at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:99)
    at [email protected]//io.undertow.server.Connectors.executeRootHandler(Connectors.java:376)
    at [email protected]//io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
    at [email protected]//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at [email protected]//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
    at [email protected]//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
    at [email protected]//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.NullPointerException
    at deployment.JSFJPA_HelloWorld_war_exploded.war//dao.ClientDAO.findall(ClientDAO.java:43)
    at deployment.JSFJPA_HelloWorld_war_exploded.war//controller.ClientBean.AllClients(ClientBean.java:41)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at [email protected]//javax.el.ELUtil.invokeMethod(ELUtil.java:245)
    at [email protected]//javax.el.BeanELResolver.invoke(BeanELResolver.java:338)
    at [email protected]//javax.el.CompositeELResolver.invoke(CompositeELResolver.java:198)
    at [email protected]//com.sun.el.parser.AstValue.getValue(AstValue.java:111)
    at [email protected]//com.sun.el.parser.AstValue.getValue(AstValue.java:179)
    at [email protected]//com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:202)
    at [email protected]//org.jboss.weld.module.web.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
    at [email protected]//org.jboss.weld.module.web.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
    at [email protected]//com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:73)
    at [email protected]//javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:170)
    at [email protected]//javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:157)
    at [email protected]//javax.faces.component.UIData.getValue(UIData.java:736)
    at [email protected]//javax.faces.component.UIData.getDataModel(UIData.java:1849)
    at [email protected]//javax.faces.component.UIData.setRowIndexWithoutRowStatePreserved(UIData.java:479)
    at [email protected]//javax.faces.component.UIData.setRowIndex(UIData.java:468)
    at [email protected]//com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:57)
    at [email protected]//javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:540)
    at [email protected]//javax.faces.component.UIData.encodeBegin(UIData.java:1153)
    at [email protected]//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1644)
    at [email protected]//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
    at [email protected]//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
    at [email protected]//com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:468)
    at [email protected]//com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:170)
    at [email protected]//javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:132)
    at [email protected]//javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:132)
    at [email protected]//com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:102)
    at [email protected]//com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76)
    at [email protected]//com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:199)
    at [email protected]//javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:708)
    ... 49 more

如果您有任何建议或意见,欢迎阅读。我才刚刚开始学习这项技术。

java hibernate jpa cdi inject
1个回答
0
投票

首先,如果要使用CDI,可以避免使用静态工厂:

@PersistenceContext(unitName = "jpa")
private EntityManager em;

@Produces
public EntityManager getEntityManager(){
    return em;
}

在您的WEB-INF目录中放入beans.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" >

</beans>

这里是文档:

当您部署Java EE应用程序时,CDI会在bean存档中查找bean。 Bean归档文件是包含CDI运行时可以管理和注入的Bean的任何模块。 Bean存档有两种:显式Bean存档和隐式Bean存档。

显式bean归档文件是一个包含bean.xml部署描述符的归档文件,该描述符可以是一个空文件,不包含版本号,或者包含bean-discovery-mode属性设置为all的版本号1.1。

隐式bean归档文件是一个归档文件,其中包含一些使用范围类型进行注释的bean,不包含beans.xml部署描述符,或者包含将bean-discovery-mode属性设置为带注释的bean.xml部署描述符。

在隐式存档中,CDI只能管理和注入使用范围类型注释的bean。

现在可以使用

@Inject
private EntityManager em;
© www.soinside.com 2019 - 2024. All rights reserved.