14

I am using Hibernate 4.2.21 on websphere 8.5.5.4 running on Java 6

Database: Microsoft SQL Server 2012

Sometimes, when I try to update an entity using the following code:

this.transaction.begin();
// lots of lines of code here before the merge
merge(carentrypermitrequest);
this.transaction.commit(); // exception here

I get the following exception:

javax.transaction.RollbackException
    at com.ibm.tx.jta.impl.TransactionImpl.stage3CommitProcessing(TransactionImpl.java:1268)
    at com.ibm.tx.jta.impl.TransactionImpl.processCommit(TransactionImpl.java:1042)
    at com.ibm.tx.jta.impl.TransactionImpl.commit(TransactionImpl.java:963)
    at com.ibm.ws.tx.jta.TranManagerImpl.commit(TranManagerImpl.java:439)
    at com.ibm.tx.jta.impl.TranManagerSet.commit(TranManagerSet.java:191)
    at com.ibm.ws.tx.jta.UserTransactionImpl.commit(UserTransactionImpl.java:302)
    at com.dataserve.mci.bean.license.CarEntryPermitRequestBean.completeAction(CarEntryPermitRequestBean.java:1525)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
    at java.lang.reflect.Method.invoke(Method.java:611)
    at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:328)
    at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:341)
    at org.jboss.el.parser.AstPropertySuffix.invoke(AstPropertySuffix.java:58)
    at org.jboss.el.parser.AstValue.invoke(AstValue.java:96)
    at org.jboss.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(Unknown Source)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(Unknown Source)
    at com.sun.faces.application.ActionListenerImpl.processAction(Unknown Source)
    at org.primefaces.application.DialogActionListener.processAction(DialogActionListener.java:45)
    at javax.faces.component.UICommand.broadcast(Unknown Source)
    at javax.faces.component.UIViewRoot.broadcastEvents(Unknown Source)
    at javax.faces.component.UIViewRoot.processApplication(Unknown Source)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(Unknown Source)
    at com.sun.faces.lifecycle.Phase.doPhase(Unknown Source)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(Unknown Source)
    at javax.faces.webapp.FacesServlet.service(Unknown Source)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1230)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:779)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:478)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:136)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:97)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:100)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91)
    at com.filenet.ae.toolkit.server.servlet.filter.PostprocessorFilter.doFilter(PostprocessorFilter.java:38)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91)
    at com.filenet.ae.toolkit.server.servlet.filter.ContainerBasedFilter.doFilter(ContainerBasedFilter.java:218)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91)
    at com.filenet.ae.toolkit.server.servlet.filter.PreprocessorFilter.doFilter(PreprocessorFilter.java:91)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91)
    at com.filenet.ae.toolkit.server.servlet.filter.SecurityPluginFilter.doFilter(SecurityPluginFilter.java:202)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91)
    at com.filenet.ae.toolkit.server.servlet.filter.ThreadLocalCleanupFilter.doFilter(ThreadLocalCleanupFilter.java:50)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91)
    at com.dataserve.common.CompatibleFilter.doFilter(CompatibleFilter.java:53)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:964)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1104)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3901)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:981)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:287)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1865)

This is how I get the session factory:

protected SessionFactory getSessionFactory() {
        try {
            return (SessionFactory) new InitialContext().lookup("SessionFactory");
        } catch (Exception e) {
            log.error("Could not locate SessionFactory in JNDI", e);
            throw new IllegalStateException("Could not locate SessionFactory in JNDI");
        }
    }

This is how I get the transaction:

public final UserTransaction transaction = getUserTransaction();

protected UserTransaction getUserTransaction() {
        try {
            return (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
        } catch (NamingException e) {
            e.printStackTrace();
            System.err.println("Could not locate UserTransaction in JNDI" + e.getMessage());
            throw new IllegalStateException("Could not locate UserTransaction in JNDI");
        }
    }

Here is the merge method:

public CarEntryPermitRequest merge(CarEntryPermitRequest detachedInstance) {
            try {
                CarEntryPermitRequest result = (CarEntryPermitRequest) sessionFactory.getCurrentSession()
                        .merge(detachedInstance);
                return result;
            } catch (RuntimeException re) {
                throw re;
            }
        }

and the completeAction() method:

public void completeAction() {

        try {

            Map fields = new HashMap();

            RequestContext requestContext = RequestContext.getCurrentInstance();
            RequestContext.getCurrentInstance().addCallbackParam("isValid", Boolean.valueOf(true));

            
            this.transaction.begin();

            if (stepNumber == null) {

                if (numberOfUploadedFiles < 2) {
                    addErrorMessage("error1", null, true);
                    return;
                }
                requestContext.addCallbackParam("step", new Integer(1));
                requestContext.addCallbackParam("isValid2", true);

                if (carentrypermitrequest == null)
                    carentrypermitrequest = new CarEntryPermitRequest();

                carentrypermitrequest.setRequesterUserName(loggedInUserId);
                carentrypermitrequest.setRequesterName(empName);
                carentrypermitrequest.setRequesterDepartmentName(empDept);
                carentrypermitrequest.setRequesterMobile(empMobile);
                carentrypermitrequest.setRequesterEmail(empEmail);
                carentrypermitrequest.setRequestDate(new Date());
                carentrypermitrequest.setRequestStatus(CarEntryPermitRequestStatusEnum.PENDING.getValue());

                if (destination == null) {

                    addErrorMessage("error2", null, true);
                    requestContext.addCallbackParam("isValid", Boolean.valueOf(false));
                    requestContext.addCallbackParam("isValid2", false);
                    this.transaction.commit();
                    return;
                }

                if (empName == null || empName.equals("")) {

                    addErrorMessage("error3", null, true);
                    requestContext.addCallbackParam("isValid", Boolean.valueOf(false));
                    requestContext.addCallbackParam("isValid2", false);
                    this.transaction.commit();
                    return;
                }

                if (empMobile == null || empMobile.equals("")) {

                    addErrorMessage("error4", null, true);
                    requestContext.addCallbackParam("isValid", Boolean.valueOf(false));
                    requestContext.addCallbackParam("isValid2", false);
                    this.transaction.commit();
                    return;
                }

                if (empBuild.equals("error5")) {
                    addErrorMessage("error6", null, true);
                    requestContext.addCallbackParam("isValid", Boolean.valueOf(false));
                    requestContext.addCallbackParam("isValid2", false);
                    this.transaction.commit();
                    return;
                }

                try {
                    if (carcategoryvalue == -1 || carcategoryvalue == null || cartypevalue == null
                            || cartypevalue == 0) {
                        addErrorMessage("error7", null,
                                true);
                        requestContext.addCallbackParam("isValid", Boolean.valueOf(false));
                        requestContext.addCallbackParam("isValid2", false);
                        this.transaction.commit();
                        return;
                    }
                } catch (Exception e) {
                    AppLogger.Log(e);
                    addErrorMessage("error8", null, true);
                    requestContext.addCallbackParam("isValid", Boolean.valueOf(false));
                    this.transaction.commit();
                    return;
                }

                if (plateNumerSplited[0].trim().equals("") || plateNumerSplited[1].trim().equals("")) {
                    addErrorMessage("error9", null, true);
                    requestContext.addCallbackParam("isValid", Boolean.valueOf(false));
                    requestContext.addCallbackParam("isValid2", false);
                    this.transaction.commit();
                    return;
                }

                platenumber = getPlateString(plateNumerSplited);

                if (carentrypermitrequesthome.isPlateHasPendingRequest(platenumber)) {
                    addErrorMessage("error10", null,
                            true);
                    requestContext.addCallbackParam("isValid", Boolean.valueOf(false));
                    requestContext.addCallbackParam("isValid2", false);
                    this.transaction.commit();
                    return;
                }

                if (destination.equals(DESTINATION_EMPLOYEE)) {

                    IoEmployees employee = ioemployeeHome.findByUserId(loggedInUserId);
                    if (employee != null) {
                        if (employee.getEmpMobile() == null || employee.getEmpMobile().trim().length() == 0) {
                            employee.setEmpMobile(empMobile);
                            ioemployeeHome.merge(employee);
                        }
                        carentrypermitrequest.setEmployee(employee);
                    }
                    carentrypermitrequest.setPlatenumber(platenumber);
                    if (StringUtils.isNotBlank(employeeNumber))
                        carentrypermitrequest.setEmployeeNumber(Integer.parseInt(employeeNumber.trim()));
                    if (StringUtils.isNotBlank(empExt))
                        carentrypermitrequest.setExt(Integer.parseInt(empExt.trim()));

                    CarType cartypeobj = cartypehome.findById(cartypevalue);
                    carentrypermitrequest.setCartypeId(cartypeobj);
                    carentrypermitrequest.setPermissioncase("under process");
                    CarCategory carcategoryobj = carcategoryehome.findById(carcategoryvalue);
                    carentrypermitrequest.setCarcategoryId(carcategoryobj);

                    CarColor carcolorobj = carcolorhome.findById(carcolorvalue);
                    carentrypermitrequest.setCarcolorId(carcolorobj);
                    carentrypermitrequest.setCarmodel(model);
                    carentrypermitrequest.setNotes(notes);
                    permitRequestDate = permitRequestDate.replace("/", "");
                    carentrypermitrequest.setPermitRequestDate(new Integer(permitRequestDate));

                    carentrypermitrequest.setEmpbuilding(empBuild);

                    carentrypermitrequesthome.attachDirty(carentrypermitrequest);
                    this.transaction.commit();
                    requestId = carentrypermitrequest.getCarentrypermitrequestId();
                    String subject = "aaaaaaaa  " + empName + " - bbbbbbbb : " + empMobile;

                    fields.put("F_Subject", subject);
                    fields.put("processType", PageCodeBase.PROCCESS_TYPES.CARENTRY.getCode());
                    fields.put("processID", carentrypermitrequest.getCarentrypermitrequestId());
                    fields.put("sendto", DESTINATION_EMPLOYEE);
                    fields.put("carentrypermitrequestID", carentrypermitrequest.getCarentrypermitrequestId());
                    fields.put("Building", empBuild.equals("المبنى الرئيسي") ? 1 : 2);
                    empMobileDisable = true;
                }

                if (destination.equals(DESTINATION_NOT_EMPLOYEE)) {

                    if (empDept == null || empDept.equals("")) {
                        addErrorMessage("aaaaaaaaaaa", null, true);
                        requestContext.addCallbackParam("isValid2", false);
                        this.transaction.commit();
                        return;
                    }
                    if (empNumber == null || empNumber.equals("")) {
                        addErrorMessage("vvvvvvvvvv ", null, true);
                        requestContext.addCallbackParam("isValid2", false);
                        this.transaction.commit();
                        return;
                    }

                    IoDepartments deptid = new IoDepartmentsHome().findByName(empDept);

                    carentrypermitrequest.setEmpdeptoutministry(deptid);
                    carentrypermitrequest.setEmpnameoutministry(empName);
                    carentrypermitrequest.setEmpnumoutministry(empNumber);
                    carentrypermitrequest.setEmpmobileoutministry(empMobile);
                    carentrypermitrequest.setEmpemailoutministry(empEmail);
                    carentrypermitrequest.setPlatenumber(platenumber);
                    CarType cartypeobj = cartypehome.findById(cartypevalue);
                    carentrypermitrequest.setCartypeId(cartypeobj);
                    carentrypermitrequest.setPermissioncase("تحت الأجراء");
                    CarCategory carcategoryobj = carcategoryehome.findById(carcategoryvalue);
                    carentrypermitrequest.setCarcategoryId(carcategoryobj);
                    CarColor carcolorobj = carcolorhome.findById(carcolorvalue);
                    carentrypermitrequest.setCarcolorId(carcolorobj);
                    carentrypermitrequest.setCarmodel(model);
                    carentrypermitrequest.setNotes(notes);
                    permitRequestDate = permitRequestDate.replace("/", "");
                    carentrypermitrequest.setPermitRequestDate(new Integer(permitRequestDate));

                    carentrypermitrequest.setEmpbuilding(empBuild);

                    carentrypermitrequesthome.attachDirty(carentrypermitrequest);
                    this.transaction.commit();
                    requestId = carentrypermitrequest.getCarentrypermitrequestId();
                    String subject = "gggggggggg  " + empName + " - tttttttttt: " + empMobile;

                    fields.put("F_Subject", subject);
                    fields.put("processType", PageCodeBase.PROCCESS_TYPES.CARENTRY.getCode());
                    fields.put("processID", carentrypermitrequest.getCarentrypermitrequestId());
                    fields.put("sendto", DESTINATION_NOT_EMPLOYEE);
                    fields.put("carentrypermitrequestID", carentrypermitrequest.getCarentrypermitrequestId());
                    fields.put("Building", empBuild.equals("المبنى الرئيسي") ? 1 : 2);

                    empMobileDisable = true;
                }
                processHandler.doLaunch(fields);

                String queueName = "";
                if (empBuild.equals(MAIN_BUILDING_VALUE)) {
                    queueName = MAIN_BUILDING_QUEUE;
                } else if (empBuild.equals(BUSINESS_BUILDING_VALUE)) {
                    queueName = BUSINESS_BUILDING_QUEUE;
                }
                List<String> toList = getPublicInboxUsersEmails(queueName);
                String mailSubject = "eeeeeeeeeeeee";
                String mailBody = createMailBodyForNewRequest();
                String imageName = "moamalatIcon.jpg";
                String bannerPath = NotificationThread.class.getResource(imageName).getPath();
                NotificationThread thread = new NotificationThread(toList, mailSubject, mailBody, configs, bannerPath);
                thread.start();

                String[] paramsArray = { carentrypermitrequest.getPlatenumber(), requestId.toString(),
                        GeneralUtils.getConfig("CAR_INQUIRE_URL") };
                sendSMSNotificaiton(empMobile, ProcessConstant.SMS_CODE_CAR_PASS_RECEIVED, paramsArray);

            }

            else if (stepNumber == STEP_NUMBER_EMPLOYEE_ACTION) { // security manager step
                requestContext.addCallbackParam("isValid2", true);

                Integer carentrypermitrequestID = (Integer) processHandler.getStepElement()
                        .getParameterValue("carentrypermitrequestID");

                if (dManaSecurityApprove == null || dManaSecurityApprove == 0) {

                    addErrorMessage("yyyyyyyyyy", null, true);
                    requestContext.addCallbackParam("isValid", Boolean.valueOf(false));
                    requestContext.addCallbackParam("isValid2", false);

                    return;
                }

                if ((permissiondate == null || permissiondate.trim().length() == 0 || permissionenumber == null
                        || permissionenumber.trim().length() == 0) && (dManaSecurityApprove == 1)) {

                    Boolean test = false;
                    addErrorMessage(" oooooooooooo", null, true);
                    requestContext.addCallbackParam("isValid", test);
                    requestContext.addCallbackParam("isValid2", false);
                    return;

                }

                carentrypermitrequest.setSecuritymanagernotes(securityManagerNotes);

                securityManager = new IoDepartmentsHome()
                        .findById(Integer.parseInt((configs.getProperty(ProcessConstant.DEP_Security_DEP))))
                        .getIoEmployeesByManagerid();

                carentrypermitrequest.setSecuritymanager(securityManager);

                IoEmployees actionEmployee = ioemployeeHome.findByUserId(getUserName());
                carentrypermitrequest.setActionEmployee(actionEmployee);

                if (dManaSecurityApprove.equals(1)) {

                    platenumber = getPlateString(plateNumerSplited);
                    carentrypermitrequest.setPlatenumber(platenumber);
                    CarType cartypeobj = cartypehome.findById(cartypevalue);
                    carentrypermitrequest.setCartypeId(cartypeobj);
                    CarCategory carcategoryobj = carcategoryehome.findById(carcategoryvalue);
                    carentrypermitrequest.setCarcategoryId(carcategoryobj);
                    CarColor carcolorobj = carcolorhome.findById(carcolorvalue);
                    carentrypermitrequest.setCarcolorId(carcolorobj);
                    carentrypermitrequest.setCarmodel(model);

                    carentrypermitrequest.setPermissioncase(permissioncase);
                    permissiondate = permissiondate.replace("/", "");
                    carentrypermitrequest.setPermissiondate(new Integer(permissiondate));
                    carentrypermitrequest.setPermissionenumber(new Integer(permissionenumber));
                    carentrypermitrequest.setVersionnumber(new Integer(versionnumber));
                    carentrypermitrequest.setLicenseVersion(licenseVersion);
                    carentrypermitrequest.setAccepted(1);
                    carentrypermitrequest.setAcceptDate(new Date());
                    carentrypermitrequest.setAcceptedBy(loggedInUserId);
                    carentrypermitrequest.setRequestStatus(CarEntryPermitRequestStatusEnum.ACCEPTED.getValue());
                    if (isexpireDate == true || permissioncase.equals(PERMIT_TYPE_TEMPORARY)) {
                        if (expireDate == null || expireDate.length() == 0) {
                            addErrorMessage("mmmmmmmmmmmm", null, true);
                            requestContext.addCallbackParam("isValid", Boolean.valueOf(false));
                            return;
                        }
                        String expireDatestr = expireDate.replace("/", "");
                        carentrypermitrequest.setExpiredate(new Integer(expireDatestr));

                        String hijriYear = expireDate.substring(0, 4);
                        String hijriMonth = expireDate.substring(5, 7);
                        String hijriDay = expireDate.substring(8);
                        String expireDateGreg = convertFromHijriToGreg(hijriYear, hijriMonth, hijriDay);

                        fields.put("expire", true);
                        fields.put("expireDate", expireDateGreg);

                    }

                    fields.put("decisionManaSecurityNum", 1);
                    fields.put("carentrypermitrequestID", carentrypermitrequestID);

                    processHandler.doComplete(fields);
                    sendSMSNotificaiton(empMobile, ProcessConstant.SMS_CODE_CAR_PASS, new String[] {});

                }
                if (dManaSecurityApprove.equals(2)) {

                    if (showSecurityManSec && StringUtils.isBlank(securityManagerNotes)) {
                        addErrorMessage("qqqqqqqqqq", null, true);
                        requestContext.addCallbackParam("isValid", Boolean.valueOf(false));
                        requestContext.addCallbackParam("isValid2", false);
                        return;
                    }
                    carentrypermitrequest.setRejectDate(new Date());
                    carentrypermitrequest.setRejectedBy(loggedInUserId);
                    carentrypermitrequest.setRejectReason(securityManagerNotes.trim());
                    carentrypermitrequest.setRequestStatus(CarEntryPermitRequestStatusEnum.REJECTED.getValue());
                    fields.put("refusedfrom", 1);
                    fields.put("decisionManaSecurityNum", 2);
                    fields.put("carentrypermitrequestID", carentrypermitrequestID);
                    processHandler.doComplete(fields);
                    String rejectReason = securityManagerNotes;
                    if (securityManagerNotes.length() > 20) {
                        rejectReason = securityManagerNotes.substring(0, 20) + "...";
                    }
                    String[] paramsArray = { carentrypermitrequest.getPlatenumber(), rejectReason };
                    sendSMSNotificaiton(empMobile, ProcessConstant.SMS_CODE_CAR_PASS_REJECTED, paramsArray);
                }

                if (dManaSecurityApprove.equals(3)) {

                    if (selectedEmp != null) {

                        fields.put("SecurityEmp", new String[] { selectedEmp });
                    }
                    fields.put("decisionManaSecurityNum", 3);
                    fields.put("carentrypermitrequestID", carentrypermitrequestID);
                    processHandler.doComplete(fields);
                }

                loadCredentials(
                        (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest());

                // sometimes this throws rollbackexception
                carentrypermitrequesthome.merge(carentrypermitrequest);
                // carentrypermitrequesthome.attachDirty(carentrypermitrequest);
                this.transaction.commit();
            }

        } catch (Exception e) {
            AppLogger.Log("######### EXCEPTION WITH CAR ENTRY REQUEST NUMBER: "
                    + carentrypermitrequest.getCarentrypermitrequestId() + " WITH USER: " + loggedInUserId
                    + ",stepNumber: " + stepNumber + ",permissionNumber: " + permissionenumber
                    + ",getTranscationStatus: " + getTranscationStatus());
            AppLogger.Log(e);
            RequestContext.getCurrentInstance().addCallbackParam("isValid", Boolean.valueOf(false));
            RequestContext.getCurrentInstance().addCallbackParam("error", true);
        }
    }

I want to know what is causing the RollbackException, since the thrown exception doesn't contain any details other than those posted above.

Mahmoud Saleh
  • 33,303
  • 119
  • 337
  • 498
  • The root cause must be an exception – Jens Aug 29 '18 at 06:50
  • @Jens, i am sorry,i don't understand, i want to find what is causing the RollbackException so that i can fix it – Mahmoud Saleh Aug 29 '18 at 07:04
  • can you post `com.dataserve.mci.bean.license.CarEntryPermitRequestBean.completeAction` – Jens Aug 29 '18 at 07:23
  • @Jens it doesn't contain anything interesting like file processing or webservice call, just based on some if conditions set some values in the object. – Mahmoud Saleh Aug 29 '18 at 12:08
  • what i want to know, is RollbackException thrown for data violation error or timeout error or something else ? – Mahmoud Saleh Aug 29 '18 at 12:10
  • @Jens, anyway i added the method – Mahmoud Saleh Aug 29 '18 at 12:45
  • Have you tried to call getCause() and getMessage() methods of your RollbackException? – user3714601 Aug 29 '18 at 18:44
  • This is not the full stacktrace. Could you please add the full exception from the logs? – Arnold Galovics Sep 02 '18 at 16:37
  • @galovics, this is the only exception i get from e.printStackTrace, that's why i am saying that it's weird. – Mahmoud Saleh Sep 03 '18 at 05:41
  • There are some logging properties from Hibernate you can set to show any SQL it generates as it flushes them to the SQL engine. If I recall there are two properties. One to show the SQL and another one to show variable bindings. If you turn those on you should be able to isolate whether there is a specific offending statement that's issued that's causing rollback and the SQL bindings will tell your what the params are so you can make sense of why. – Atmas Mar 26 '21 at 04:54

3 Answers3

4

In the past I have been struggling with the same exact issue: I was trying to update an entity with some new data and kept receiving this RollBackException without any trace.

After hours of debugging into the source code of Hibernate I had found out that another completely different exception was thrown previously from within the Hibernate's source code and swallowed inside an empty catch block and disappearing from any external view. This broke the EntityManager that i was using to merge my data.

In particular, Hibernate was trying to instance another entity required in the process but couldn't find the default public constructor.

How Hibernate's code could have lines of code containing empty catch blocks is still unknown to me. The version that i was using is 4.3.5.Final.

I guess you are experiencing the same issue: some exception, maybe of different nature that the one that I faced (the lack of a public default constructor), is thrown from the hibernate layer, there-in catched and then not managed anyhow.

I suggest that you operate the same process:

Download the source code of Hibernate and iterate there-in throughout the methods that are called by your procedure, especially keeping an eye open for empty catch blocks. PLEASE NOTE that in my case the empty catch block did not belong to a method visible on the stack trace of the RollBackException !



Here is a link to the post that i created at the time on CodeRanch to discuss my issue:

CodeRanch - RollbackException thrown when adding ManyToOne relationship

Luca Tampellini
  • 1,759
  • 17
  • 23
0

I think you must initialize the transaction every time but you declared the transaction as final in this line:

public final UserTransaction transaction = getUserTransaction();

So change your code to generate a new transaction object according to your connection object every time you need to begin a transaction.

Mostafa Vatanpour
  • 1,328
  • 13
  • 18
0

If you haven't tried this already, it may point to a pattern/problem faster if you turn up SQL Parameter binding and statement logging. Then you can see if there are certain statements or values that consistently appear just before you see rollbacks. There are two log4j properties to set to show this information. Here is a page that details it pretty well if you want to give it a go.

https://thorben-janssen.com/hibernate-tips-how-to-log-sql-statements-and-their-parameters/

Atmas
  • 2,389
  • 5
  • 13