开发者

Delete database rows with EJB 3.0

I want to delete a row in a database, so i created an EJB that does it for me

@Stateless(name = "ejbs/AdminAcountEJB")
public class AdminAcountEJB implements IAdminAcountEJB  {

    @PersistenceContext
    private EntityManager entityManager;

    public void deleteRecord(Record record) {
                    entityManager.remove(record);
    }
}

I did not create TransactionEntity object and then use the begin() method, because as i understood, the EJB's are already transaction secured.

To see if it works in the user interface(A JSF 2.0 page) i created a datatable with a column with a delete command link and triggered it from a backingbean that is connected to the EJB:

page

<h:dataTable value="#{managementBB.retrieveRecords()}" var="record">
                   ...
                    <h:column>
    <h:commandLink value="X" action="#{managementBB.deleteRow(record)}"/>
                    </h:column>
</h:dataTable>

backing bean

 @Named("managementBB")
@SessionScoped
public class ManagementBB implements Serializable{

    @EJB
    private IAdminAcountEJB managementEJB;

    //...

    public String deleteRow(Record record) {

        managementEJB.deleteRecord(record);
        return "manage?faces-redirect=true;";
    }

This is the error i see in the console when ciclking the link to delete a row:

WARNING: StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception javax.faces.el.EvaluationException: javax.ejb.EJBException at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102) at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) at javax.faces.component.UICommand.broadcast(UICommand.java:315) at javax.faces.component.UIData.broadcast(UIData.java:912) at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:775) at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1267) at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandard开发者_JAVA技巧Pipeline.java:85) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57) at com.sun.grizzly.ContextTask.run(ContextTask.java:69) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309) at java.lang.Thread.run(Thread.java:662) Caused by: javax.ejb.EJBException at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5119) at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5017) at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4805) at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2004) at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1955) at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:198) at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:84) at $Proxy162.deleteRecord(Unknown Source) at backingbeans.ManagementBB.deleteRow(ManagementBB.java:46) 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 org.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:304) at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:54) at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:163) at org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:298) at org.jboss.weld.bean.proxy.ClientProxyMethodHandler.invoke(ClientProxyMethodHandler.java:113) at org.jboss.weld.util.CleanableMethodHandler.invoke(CleanableMethodHandler.java:43) at backingbeans.ManagementBB_$$_javassist_132.deleteRow(ManagementBB_$$_javassist_132.java) 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.invokeMethod(BeanELResolver.java:737) at javax.el.BeanELResolver.invoke(BeanELResolver.java:467) at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:246) at com.sun.el.parser.AstValue.invoke(AstValue.java:228) at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297) at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:43) at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:72) at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:98) at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) ... 33 more Caused by: java.lang.IllegalArgumentException: Entity must be managed to call remove: entities.Record@df8b3d, try merging the detached and try the remove again. at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.performRemove(UnitOfWorkImpl.java:3539) at org.eclipse.persistence.internal.jpa.EntityManagerImpl.remove(EntityManagerImpl.java:435) at com.sun.enterprise.container.common.impl.EntityManagerWrapper.remove(EntityManagerWrapper.java:292) at ejbs.AdminAcountEJB.deleteRecord(AdminAcountEJB.java:23) 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 org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1056) at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1128) at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5292) at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:615) at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:797) at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:567) at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:47) at sun.reflect.GeneratedMethodAccessor87.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:858) at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:797) at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:567) at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:157) at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:139) at sun.reflect.GeneratedMethodAccessor86.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:858) at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:797) at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:367) at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5264) at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5252) at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:190) ... 60 more

As you see i use CDI for beans(@Named) instead of @ManagedBeans but i hope that is not the reason. Also i would like to mention that in my database, i have an independent table, that is not related at all to the Record table, could this affect?


The answer can be found in the stacktrace itself within the lines:

Caused by: java.lang.IllegalArgumentException: Entity must be managed to call remove: entities.Record@df8b3d, try merging the detached and try the remove again.

EntityManager.remove requires that the reference passed in as an argument be a managed entity, i.e. the object must present in the persistence context. If you are passing in an entity reference from a JSF managed bean or a CDI managed bean, it is still an unmanaged/detached entity, unless you have originally obtained the entity reference from the current persistence context.

To understand this further, you ought to be aware of the JPA entity lifecycle. In most cases, the managed entity that you fetch from a persistence context, is detached at the end of the transaction (i.e. when the persistence context ends). Your JSF/CDI managed beans would therefore be working with detached entities and not managed entities. When you pass the detached entity from JSF back to the EJB, invoking EntityManager.remove will result in the described IllegalArgumentException.

The solution therefore is to get the reference to a managed entity by using the detached entity, using EntityManager.merge (which merges the contents of the detached entity with the persistence context, and returns a reference to a managed entity) or EntityManager.find (which returns a managed entity from the persistence context, if it is present there). I prefer using EntityManager.find in the scenario where it is possible for the detached entity to be modified - when a detached entity has relationships with other entities, then the MERGE might be cascaded while the REMOVE operation might not, if you are not careful in defining what operations must be cascaded.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜