我有一个使用JPA的Java EE项目。 当我的服务器启动时,我的表是由hibernate自动生成的,所以我的entites是正确的。 我现在需要使用entitymanager插入/更新数据。 当我使用带注释的实体管理器或使用entityManagerFactory的标准实体管理器时,我得到了NullPointer异常。
我的persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
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">
<persistence-unit name="LogmonPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/LogmonDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
我的abstractDAO课程:
package com.st.safir.LogMonitoring.ejb;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.EntityManager;
/**
* @author benoit brayer
*
* @param <E>
* The class entity needed to be mapped
* @param <PK>
* The primary key type for this class
*/
public abstract class AbstractDAO<E
extends Serializable, PK extends Serializable> {
/** */
private final transient Class<E> mEntityClass;
/**
* @param entityClass the entity needed to be mapped by the dao class
*/
public AbstractDAO(final Class<E> entityClass) {
mEntityClass = entityClass;
}
/**
* @return the EntityManager object corresponding to the mapped entity class
*/
protected abstract EntityManager getEntityManager();
/**
* @return all objects mapped by entity
*/
protected abstract Collection<E> getAll();
/**
* @param entity an instance of the entity needed to be add database
*/
public final void create(final E entity) {
final EntityManager entityManager = getEntityManager();
entityManager.persist(entity);
}
/**
* @param id the id of the desired entity object
* @return the entity object matching the specified id
*/
public final E getById(final PK id) {
return getEntityManager().find(mEntityClass, id);
}
}
我的EJB像我的模型一样使用:
package com.st.safir.LogMonitoring.ejb;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.st.safir.LogMonitoring.jpa.User;
/**
* @author benoit brayer
*/
@Stateless(name = "userEJB")
public class UserEJB extends AbstractDAO<User, Long> {
/** */
@PersistenceContext(unitName = "LogmonPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
/** */
public UserEJB() {
super(User.class);
}
@SuppressWarnings("unchecked")
@Override
protected Collection<User> getAll() {
Query query = em.createQuery("SELECT u from WEB_USER u");
return (Collection<User>) query.getResultList();
}
/**
* @param username the username matching the desired entity object
* @return the entity object corresponding to the database row
*/
public final User getUserByUsername(final String username) {
Query query = em
.createQuery("SELECT u from WEB_USER u where u.username = ?1")
.setParameter(1, username);
return (User) query.getSingleResult();
}
}
错误日志:
com.sun.faces.mgbean.ManagedBeanCreationException: Cant instantiate class: com.st.safir.LogMonitoring.jsf.index.IndexBean.
at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:193)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102)
at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:72)
at org.apache.el.parser.AstValue.getValue(AstValue.java:147)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at com.sun.faces.facelets.el.ELText$ELTextVariable.writeText(ELText.java:227)
at com.sun.faces.facelets.el.ELText$ELTextComposite.writeText(ELText.java:150)
at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:85)
at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
at com.sun.faces.facelets.compiler.UILeaf.encodeAll(UILeaf.java:183)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:125)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
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:594)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:840)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:622)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:560)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:488)
at org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:706)
at org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:677)
at org.apache.jsp.index_jsp._jspService(index_jsp.java:64)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:326)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:253)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248)
at com.c2alliance.commons.sso.client.filter.AllianceCASAuthorizationFilter.doFilter(AllianceCASAuthorizationFilter.java:215)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248)
at edu.yale.its.tp.cas.client.filter.CASFilter.doFilter(CASFilter.java:473)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50)
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at com.st.safir.LogMonitoring.ejb.UserEJB.getUserByUsername(UserEJB.java:43)
at com.st.safir.LogMonitoring.jsf.controller.UserControllerBean.isUserFirstLogin(UserControllerBean.java:42)
at com.st.safir.LogMonitoring.jsf.controller.UserControllerBean.webAppUserAuthentication(UserControllerBean.java:69)
at com.st.safir.LogMonitoring.jsf.index.IndexBean.<init>(IndexBean.java:51)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188)
... 59 more
提前谢谢。
此致
编辑:
控制器调用我的JSF托管bean来处理业务逻辑: 包com.st.safir.LogMonitoring.jsf.controller;
import java.io.Serializable;
import javax.annotation.ManagedBean;
import javax.faces.bean.RequestScoped;
import com.st.safir.LogMonitoring.ejb.UserEJB;
import com.st.safir.LogMonitoring.jpa.User;
/**
* @author benoit brayer
*/
@RequestScoped
@ManagedBean
public class UserControllerBean implements Serializable {
/**
* Generated attribute for Serialization.
*
* @attribute serialVersionUID serialisation id
* @see java.io.Serializable
*/
private static final long serialVersionUID = 1L;
/** */
private User mUser;
/**
* @return true if it is the user first login & false if the user has
* already an account
* @param username
* the user username
*/
public final boolean isUserFirstLogin(final String username) {
Boolean firstLogin = true;
UserEJB userEjb = new UserEJB();
User user = userEjb.getUserByUsername(username);
if (user != null) {
firstLogin = false;
}
return firstLogin;
}
/**
* Operations called after getting the usename
* of the user who logged-in using SSO.
* @param username
* the user username
*/
public final void webAppUserAuthentication(final String username) {
User user = null;
UserEJB userEjb = new UserEJB();
if (isUserFirstLogin(username)) {
user = new User();
user.setUsername(username);
userEjb.create(user);
} else {
user = userEjb.getUserByUsername(username);
}
this.setUser(user);
}
.... other stuff
我的index.xhtml页面的indexbean托管bean:
/** JSF Facelet
* @author Benoit Brayer
* @imports java.io.Serializable;
* @imports javax.faces.bean.ManagedBean;
* @imports javax.faces.bean.RequestScoped;
* @import javax.faces.context.FacesContext;
* @import javax.servlet.http.HttpServletRequest;
*/
package com.st.safir.LogMonitoring.jsf.index;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import com.st.safir.LogMonitoring.jsf.controller.UserControllerBean;
/**
* JSF ManagedBean for index page.
*/
@RequestScoped
@ManagedBean(name = "indexBean")
public class IndexBean implements Serializable {
/**
* Generated attribute for Serialization.
*
* @attribute serialVersionUID serialisation id
* @see java.io.Serializable
*/
private static final long serialVersionUID = 1L;
/**
* Returns the name of the jsf Bean.
*/
private String mNom = "indexBean";
/** */
private UserControllerBean userController = new UserControllerBean();
/**
* @return the name of the servlet
*/
public final String getNom() {
return mNom;
}
/** IndexBean constructor. */
public IndexBean() {
userController.webAppUserAuthentication((((HttpServletRequest)
FacesContext.getCurrentInstance().getExternalContext().getRequest())
.getUserPrincipal()).toString());
}
... other stuff
我最终使用以下方法解决了一半问题:
private EntityManager em = (EntityManager) Persistence
.createEntityManagerFactory("LogmonPU")
.createEntityManager();
而不是:
@PersistenceContext(unitName = "LogmonPU")
private EntityManager em;
在我的EJB文件中。
将这些行添加到我的persistence.xml中:
<class>com.st.safir.LogMonitoring.jpa.User</class>
和
<property name="hibernate.transaction.factory_class" value="org.hibernate.transaction.JDBCTransactionFactory" />
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform" />
我的实体管理器不是更多null但我仍然无法插入数据库。 此后我的数据库中没有显示行。 我的jboss日志:
janv./17 15:20:19,710 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Hibernate:
janv./17 15:20:19,712 INFO [stdout] (http-localhost-127.0.0.1-8080-1) select
janv./17 15:20:19,715 INFO [stdout] (http-localhost-127.0.0.1-8080-1) S_INC_TUSER.nextval
janv./17 15:20:19,717 INFO [stdout] (http-localhost-127.0.0.1-8080-1) from
janv./17 15:20:19,719 INFO [stdout] (http-localhost-127.0.0.1-8080-1) dual
这基本上是我使用oracle数据库来增加行数的序列。
答案 0 :(得分:0)
最终解决问题
为了最终解决问题,我改变了我的persistence.xml:
<persistence-unit name="LogmonPU" transaction-type="RESOURCE_LOCAL">
从现在起我也使用我的实体经理:
public final User create(final User entity) {
EntityManager entityManager = getEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.getTransaction().commit();
entityManager.close();
return entity;
}
那是夸张的,但我终于解决了--.-' 感谢有助于我解决的评论。