0

我的 EJB / JPA 项目有问题。我使用 netbeans、weblogic 10g 和 Java EE 应用程序。

我的问题是,我创建“来自数据库的实体类”,然后创建“实体类的会话 bean”,这基本上是我的门面。

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

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

这是我的 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();
        }
    }
}

这是我的 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());
            }
        }
    }
}

最后我的例外:

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)

如果有人可以在这个问题上帮助我,我将不胜感激。

4

1 回答 1

0

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

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

  2. 将以下行添加到文件中

    @rem JAR AGREGADOS PARA EL SOPORTE DE JPA2.0 EN WLS 设置 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. 重新启动 de weblogic 服务器

对于注入持久性单元,您可以使用

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

在你的门面或道课上

您不需要 EntityManagerFactory 注入。

我希望这对你有帮助。

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

于 2013-02-25T16:55:12.597 回答