使用weblogic 10g bean注入jpa / ejb的空指针异常

时间:2023-01-19 21:40:22

I have a problem with my EJB / JPA project. I use netbeans, weblogic 10g and Java EE app.

我的EJB / JPA项目有问题。我使用netbeans,weblogic 10g和Java EE app。

My problem is, I create "Entity classes from database" and after that I create "session beans for entity classes" which are basically my facades.

我的问题是,我创建了“数据库中的实体类”,之后我创建了“实体类的会话bean”,这基本上就是我的外观。

Then I go over my war project and say "JSF pages for entity classses" Netbeans creates all the classes nicely.

然后我回顾我的战争项目并说“实体类的JSF页面”Netbeans很好地创建了所有类。

At the beginning it says I have to have a persistence provider and for that aim I add the library "Hibernate JPA".

一开始它说我必须有一个持久性提供程序,为此我添加了库“Hibernate JPA”。

Here is my ArchJpaController:

这是我的ArchJpaController:

package JPAControllerS;

import JPAControllerS.exceptions.NonexistentEntityException;
import JPAControllerS.exceptions.RollbackFailureException;
import entities.Arch;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.transaction.UserTransaction;



public class ArchJpaController implements Serializable {

    public ArchJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Arch arch) throws RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            em.persist(arch);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Arch arch) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            arch = em.merge(arch);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = arch.getId();
                if (findArch(id) == null) {
                    throw new NonexistentEntityException("The arch with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Arch arch;
            try {
                arch = em.getReference(Arch.class, id);
                arch.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The arch with id " + id + " no longer exists.", enfe);
            }
            em.remove(arch);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Arch> findArchEntities() {
        return findArchEntities(true, -1, -1);
    }

    public List<Arch> findArchEntities(int maxResults, int firstResult) {
        return findArchEntities(false, maxResults, firstResult);
    }

    private List<Arch> findArchEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Arch as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Arch findArch(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Arch.class, id);
        } finally {
            em.close();
        }
    }

    public int getArchCount() {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select count(o) from Arch as o");
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
}

And here is my ArchController:

这是我的ArchController:

    package JSFClasses;

import entities.Arch;
import JSFClasses.util.JsfUtil;
import JSFClasses.util.PaginationHelper;
import JPAControllerS.ArchJpaController;

import java.io.Serializable;
import java.util.ResourceBundle;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;

@ManagedBean(name = "archController")
@SessionScoped
public class ArchController implements Serializable {

    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "IBB_Latest-warPU")
    private EntityManagerFactory emf = null;
    private Arch current;
    private DataModel items = null;
    private ArchJpaController jpaController = null;
    private PaginationHelper pagination;
    private int selectedItemIndex;

    public ArchController() {
    }

    public Arch getSelected() {
        if (current == null) {
            current = new Arch();
            selectedItemIndex = -1;
        }
        return current;
    }

    private ArchJpaController getJpaController() {
        if (jpaController == null) {
            jpaController = new ArchJpaController(utx, emf);
        }
        return jpaController;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getJpaController().getArchCount();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getJpaController().findArchEntities(getPageSize(), getPageFirstItem()));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Arch) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Arch();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getJpaController().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ArchCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Arch) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getJpaController().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ArchUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Arch) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getJpaController().destroy(current.getId());
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ArchDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getJpaController().getArchCount();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getJpaController().findArchEntities(1, selectedItemIndex).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(getJpaController().findArchEntities(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(getJpaController().findArchEntities(), true);
    }

    @FacesConverter(forClass = Arch.class)
    public static class ArchControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ArchController controller = (ArchController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "archController");
            return controller.getJpaController().findArch(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Arch) {
                Arch o = (Arch) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Arch.class.getName());
            }
        }
    }
}

Finally my exception:

最后我的例外:

java.lang.NullPointerException
    at JPAControllerS.ArchJpaController.getEntityManager(ArchJpaController.java:43)
    at JPAControllerS.ArchJpaController.findArchEntities(ArchJpaController.java:132)
    at JPAControllerS.ArchJpaController.findArchEntities(ArchJpaController.java:128)
    at JSFClasses.ArchController$1.createPageDataModel(ArchController.java:66)
    at JSFClasses.ArchController.getItems(ArchController.java:166)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:261)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at com.sun.el.parser.AstValue.getValue(AstValue.java:118)
    at com.sun.el.parser.AstEqual.getValue(AstEqual.java:41)
    at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:192)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.UIComponentBase.isRendered(UIComponentBase.java:413)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1750)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:292)
    at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:27)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:43)
    at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:43)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3496)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(Unknown Source)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2180)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2086)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1406)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)

If someone could help me on this issue I would be greatly appreciated.

如果有人可以帮我解决这个问题,我将不胜感激。

1 个解决方案

#1


0  

first: What version of JPA are you using? 1.0 or 2.0? If you use 2.0, weblogic by default doesn't support it. But you can enable making following changes:

第一:你使用的是什么版本的JPA? 1.0还是2.0?如果您使用2.0,默认情况下weblogic不支持它。但您可以启用以下更改:

  1. locate the file commEnv.cmd(or sh for linux). The file is in WEBLOGIC_HOME/common/bin. Example for windows: C:\Oracle\Middleware\wlserver_10.3\common\bin

    找到文件commEnv.cmd(或sh for linux)。该文件位于WEBLOGIC_HOME / common / bin中。 Windows示例:C:\ Oracle \ Middleware \ wlserver_10.3 \ common \ bin

  2. Add the following lines to the file

    将以下行添加到该文件中

    @rem JAR AGREGADOS PARA EL SOPORTE DE JPA2.0 EN WLS set PRE_CLASSPATH=%MW_HOME%/modules/javax.persistence_1.0.0.0_2-0-0.jar;%MW_HOME%/modules/com.oracle.jpa2support_1.0.0.0_2-0.jar

    @rem JAR AGREGADOS PARA EL SOPORTE DE JPA2.0 EN WLS set PRE_CLASSPATH =%MW_HOME%/ modules / javax.persistence_1.0.0.0_2-0-0.jar;%MW_HOME%/ modules / com.oracle.jpa2support_1.0.0。 0_2-0.jar

  3. restart de weblogic server

    restart de weblogic server

For inject the persitent unit you can use

注射你可以使用的持久单位

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

On your facade or dao clasess

在你的门面或dao clasess

You don't need an EntityManagerFactory injection.

您不需要EntityManagerFactory注入。

I hope this help you.

我希望这对你有帮助。

Sorry for my english... It`s really bad .. :-(

对不起我的英文...这真的很糟.. :-(

#1


0  

first: What version of JPA are you using? 1.0 or 2.0? If you use 2.0, weblogic by default doesn't support it. But you can enable making following changes:

第一:你使用的是什么版本的JPA? 1.0还是2.0?如果您使用2.0,默认情况下weblogic不支持它。但您可以启用以下更改:

  1. locate the file commEnv.cmd(or sh for linux). The file is in WEBLOGIC_HOME/common/bin. Example for windows: C:\Oracle\Middleware\wlserver_10.3\common\bin

    找到文件commEnv.cmd(或sh for linux)。该文件位于WEBLOGIC_HOME / common / bin中。 Windows示例:C:\ Oracle \ Middleware \ wlserver_10.3 \ common \ bin

  2. Add the following lines to the file

    将以下行添加到该文件中

    @rem JAR AGREGADOS PARA EL SOPORTE DE JPA2.0 EN WLS set PRE_CLASSPATH=%MW_HOME%/modules/javax.persistence_1.0.0.0_2-0-0.jar;%MW_HOME%/modules/com.oracle.jpa2support_1.0.0.0_2-0.jar

    @rem JAR AGREGADOS PARA EL SOPORTE DE JPA2.0 EN WLS set PRE_CLASSPATH =%MW_HOME%/ modules / javax.persistence_1.0.0.0_2-0-0.jar;%MW_HOME%/ modules / com.oracle.jpa2support_1.0.0。 0_2-0.jar

  3. restart de weblogic server

    restart de weblogic server

For inject the persitent unit you can use

注射你可以使用的持久单位

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

On your facade or dao clasess

在你的门面或dao clasess

You don't need an EntityManagerFactory injection.

您不需要EntityManagerFactory注入。

I hope this help you.

我希望这对你有帮助。

Sorry for my english... It`s really bad .. :-(

对不起我的英文...这真的很糟.. :-(