cancel
Showing results for 
Search instead for 
Did you mean: 

Troubles with JPA / Activiti CDI initialisation

chris_joelly
Champ in-the-making
Champ in-the-making
Hello,

i am not sure if this is the right forum for my problem, but as it only happens
in the context of an Activiti execution i decided to post it here.

I run into troubles when i change a property on an JPA process variable from within
an service task. The owning entity is an Order having a ManyToOne relation to the
target entity OrderStatus, both entities are used in an JSF webapp outside of an
Activiti context without problems.
But when i change the OrderStatus of an Order within an service task i get the
attached exception when Activiti calls the flush() method on an EntityManager
when it tries to persist the order process variable. However, e.g. changing a
String property on the Order entity within an service task works without a problem.

The service task in question is located in an process definition which is called
periodically and checks for new orders in state NEW, and the service task should
set the state to VERIFYING that orders are not processed multiple times when the
process execution stops at an user task.

The service tasks make use of activiti:delegateExpression and the expression
resolves to an @Named @Stateless EJB. There the process variable order is fetched
from the execution and the property orderState changed. When the execution arrives
at the user task Activiti wants to persist the order process variable and then
the exception occurs stating that the JPA provider (EclipseLink from Glassfish)
can not persist the entity OrderStatus because there is already an existing entity
with that @Id.
Why does this happen? The OrderStatus which i set on the Order is fetched using
another EJB via JPA and of course exists, why does the persistence context think
that it deals with an new entity?
Strange enough this does not happen when i change the property via an JSF form.

Is there something special how Activiti treats JPA entities?

Thanks for any hint

Chris

Entities:

@Entity
public class OrderStatus extends AbstractEntity implements Serializable {
   private static final long serialVersionUID = -6122412952782603911L;
   @Column(unique = true, nullable = false, length = 20)
   private String name;
   @Column(nullable = false, length = 40)
   private String description;
   public String getName() { return name; }
   public void setName(String name) { this.name = name; }
   public String getDescription() { return description; }
   public void setDescription(String description) { this.description = description; }
}

@Entity
public class Order extends AbstractEntity implements Serializable {
   private static final long serialVersionUID = -8061887078955032972L;
   @ManyToOne(cascade={CascadeType.REFRESH}, optional = false)
   private OrderStatus status = null;
   @OneToOne(cascade=CascadeType.ALL, optional = false)
   private Payment payment = null;   
   public OrderStatus getStatus() { return status; }
   public void setStatus(OrderStatus status) { this.status = status; }
   public Payment getPayment() { return payment; }
   public void setPayment(Payment payment) { this.payment = payment; }
}

@MappedSuperclass
public abstract class AbstractEntity implements Serializable {
   private static final long serialVersionUID = 3617731729820193893L;
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   protected Long id;
   @Version
   protected int version;
   @Temporal(TemporalType.TIMESTAMP)
   protected Date createdOn;
   @Temporal(TemporalType.TIMESTAMP)
   protected Date modifiedOn;
   public Long getId() { return id; }
   public void setId(Long id) { this.id = id; }
   public int getVersion() { return version; }
   public void setVersion(int version) { this.version = version; }
   public Date getCreatedOn() { return createdOn; }
   public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; }
   public Date getModifiedOn() { return modifiedOn; }
   public void setModifiedOn(Date modifiedOn) { this.modifiedOn = modifiedOn; }
   @PrePersist
   public void initTimeStamps() {
      if (createdOn == null) {
         createdOn = new Date();
      }
      modifiedOn = createdOn;
   }
   @PreUpdate
   public void updateTimeStamp() {   modifiedOn = new Date(); }
   @Override
   public int hashCode() {
      final int prime = 31;
      int result = 1;
      result = prime * result + ((id == null) ? 0 : id.hashCode());
      return result;
   }
   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (obj == null)
         return false;
      if (getClass() != obj.getClass())
         return false;
      AbstractEntity other = (AbstractEntity) obj;
      if (id == null) {
         if (other.id != null)
            return false;
      } else if (!id.equals(other.id))
         return false;
      return true;
   }
}

Service task and process definition modifying the order:

@Named
@Stateless
public class SetVerifyingOrderTask extends AbstractServiceTask {
   private static final long serialVersionUID = 3660874744535219312L;
   @EJB
   OrderStatusEJB orderStatusService;
   @Override
   public void delegateExecute(DelegateExecution execution) throws Exception {
      Order order = (Order) execution.getVariable("order");
      OrderStatus orderState = orderStatusService.findByName("VERIFYING");
      order.setStatus(orderState);
   }
}

public abstract class AbstractServiceTask implements JavaDelegate, Serializable {
   private static final long serialVersionUID = -1271784378490107598L;
   protected static Logger logger = Logger.getLogger(AbstractServiceTask.class.getName());
   public AbstractServiceTask() { super(); }
   @Override
   public void execute(DelegateExecution execution) throws Exception {
      if (logger.isLoggable(Level.FINE)) {
         logger.fine("execution: " + execution.getId() + "/" + execution.getProcessInstanceId());
      }

      // delegate to the method providing the real work…
      delegateExecute(execution);

      if (logger.isLoggable(Level.FINE)) {
         for (String variableName : execution.getVariableNames()) {
            logger.log(
                  Level.FINE,
                  "execution result: {0} = {1}",
                  new Object[] { variableName,
                        execution.getVariable(variableName) });
         }
      }
   }
   public abstract void delegateExecute(DelegateExecution execution) throws Exception;
}

  <process id="verifyPayment" name="Verify Payment">
    <startEvent id="startevent1" name="Start"></startEvent>
    <serviceTask id="setOrderToVerifying" name="Set order state to verifying" activiti:delegateExpression="#{setVerifyingOrderTask}"></serviceTask>
    <serviceTask id="checkPaymentMethod" name="Check payment method" activiti:delegateExpression="#{checkPaymentMethodTask}"></serviceTask>
    <exclusiveGateway id="exclusivegateway1" name="Exclusive Gateway"></exclusiveGateway>
    <userTask id="verifyPaymentData" name="Verify payment data" activiti:formKey="acceptanceOfOrder/verifyPaymentData"></userTask>
    <exclusiveGateway id="exclusivegateway2" name="Exclusive Gateway"></exclusiveGateway>
    <serviceTask id="setOrderToAccepted" name="Set order state to accepted" activiti:delegateExpression="#{acceptOrderTask}"></serviceTask>
    <endEvent id="endevent1" name="End"></endEvent>
    <sequenceFlow id="flow24" name="" sourceRef="startevent1" targetRef="setOrderToVerifying"></sequenceFlow>
    <sequenceFlow id="flow25" name="" sourceRef="setOrderToVerifying" targetRef="checkPaymentMethod"></sequenceFlow>
    <sequenceFlow id="flow3" name="" sourceRef="checkPaymentMethod" targetRef="exclusivegateway1"></sequenceFlow>
    <sequenceFlow id="flow4" name="#{orderAlreadyPayed}" sourceRef="exclusivegateway1" targetRef="exclusivegateway2">
      <conditionExpression xsi:type="tFormalExpression"><![CDATA[#{orderAlreadyPayed}]]></conditionExpression>
    </sequenceFlow>
    <sequenceFlow id="flow9" name="#{!orderAlreadyPayed}" sourceRef="exclusivegateway1" targetRef="verifyPaymentData">
      <conditionExpression xsi:type="tFormalExpression"><![CDATA[#{!orderAlreadyPayed}]]></conditionExpression>
    </sequenceFlow>
    <sequenceFlow id="flow27" name="" sourceRef="verifyPaymentData" targetRef="exclusivegateway2"></sequenceFlow>
    <sequenceFlow id="flow5" name="" sourceRef="exclusivegateway2" targetRef="setOrderToAccepted"></sequenceFlow>
    <sequenceFlow id="flow26" name="" sourceRef="setOrderToAccepted" targetRef="endevent1"></sequenceFlow>
  </process>

Service task and process definition checking for new orders:

@Named
@Stateless
public class CheckNewOrdersTask extends AbstractServiceTask {
   private static final long serialVersionUID = -8300047795625617499L;
   @EJB
   OrderEJB orderService;
   @EJB
   OrderStatusEJB orderStatusService;
   @Override
   public void delegateExecute(DelegateExecution execution) throws Exception {
      OrderStatus stateNew = orderStatusService.findByName("NEW");
      List<Order> orders = orderService.findByStatus(stateNew);
      if (!orders.isEmpty()) {
         execution.setVariable("newOrders", orders);
         execution.setVariable("newOrdersAvailable", Boolean.TRUE);
      } else {
         execution.setVariable("newOrdersAvailable", Boolean.FALSE);
      }
   }
}

  <process id="newOrderChecker" name="New order checker">
    <startEvent id="timerstartevent1" name="Timer start">
      <timerEventDefinition>
        <timeCycle>R/PT2M</timeCycle>
      </timerEventDefinition>
    </startEvent>
    <serviceTask id="checkOrderAvailable" name="Check new orders available" activiti:delegateExpression="#{checkNewOrdersTask}"></serviceTask>
    <exclusiveGateway id="exclusivegateway1" name="Exclusive Gateway"></exclusiveGateway>
    <endEvent id="endevent1" name="End"></endEvent>
    <callActivity id="callVerifyPayment" name="Verify payment" calledElement="verifyPayment">
      <extensionElements>
        <activiti:in source="newOrder" target="order"></activiti:in>
      </extensionElements>
      <multiInstanceLoopCharacteristics isSequential="false" activiti:collection="newOrders" activiti:elementVariable="newOrder"></multiInstanceLoopCharacteristics>
    </callActivity>
    <exclusiveGateway id="exclusivegateway2" name="Exclusive Gateway"></exclusiveGateway>
    <sequenceFlow id="flow1" name="" sourceRef="timerstartevent1" targetRef="checkOrderAvailable"></sequenceFlow>
    <sequenceFlow id="flow2" name="" sourceRef="checkOrderAvailable" targetRef="exclusivegateway1"></sequenceFlow>
    <sequenceFlow id="noNewOrdersFlow" name="#{!newOrdersAvailable}" sourceRef="exclusivegateway1" targetRef="exclusivegateway2">
      <conditionExpression xsi:type="tFormalExpression"><![CDATA[#{!newOrdersAvailable}]]></conditionExpression>
    </sequenceFlow>
    <sequenceFlow id="newOrdersFlow" name="#{newOrdersAvailable}" sourceRef="exclusivegateway1" targetRef="callVerifyPayment">
      <conditionExpression xsi:type="tFormalExpression"><![CDATA[#{newOrdersAvailable}]]></conditionExpression>
    </sequenceFlow>
    <sequenceFlow id="flow3" name="" sourceRef="callVerifyPayment" targetRef="exclusivegateway2"></sequenceFlow>
    <sequenceFlow id="flow4" name="" sourceRef="exclusivegateway2" targetRef="endevent1"></sequenceFlow>
  </process>

Activiti Config:

<!– use data source from the application server –>
<jee:jndi-lookup jndi-name="jdbc/Erp" id="dataSource" />

<!– use transaction manager from the application server –>
<jee:jndi-lookup jndi-name="java:appserver/TransactionManager" id="transactionManager" />

<!– integrate Activiti with CDI and JTA –>
<bean id="processEngineConfiguration"
   class="org.activiti.cdi.CdiJtaProcessEngineConfiguration">

   <!– config for JTA managed persistence –>
   <property name="dataSource" ref="dataSource" />
   <property name="transactionManager" ref="transactionManager"/>
   <property name="transactionsExternallyManaged" value="true" />
   
   <property name="jpaPersistenceUnitName" value="erp.web" />
   <property name="jpaHandleTransaction" value="false" />
   <property name="jpaCloseEntityManager" value="false" />

   <!– upgrade Activiti model if needed –>
   <property name="databaseSchemaUpdate" value="true" />
   <property name="databaseType" value="mysql" />

   <!– enable timers –>
   <property name="jobExecutorActivate" value="true" />
   
   <!– log full details to the history tables –>
   <property name="history" value="full" />
   
   <!– mail server cfg for sending mails out of a mail service task –>
   <property name="mailServerHost" value="localhost"/>
   <property name="mailServerPort" value="25"/>
   <property name="mailServerDefaultFrom" value="crm@comp.cc"/>
</bean>

Sorry for that, but i could not attach the exception as file…

FEIN: ProcessInstance[25424] executes Activity(setOrderToVerifying): org.activiti.engine.impl.bpmn.behavior.ServiceTaskDelegateExpressionActivityBehavior
SCHWERWIEGEND: No valid EE environment for injection of org.activiti.cdi.impl.context.DefaultBusinessProcessAssociationManager
AM FEINSTEN: Context interface javax.enterprise.context.ConversationScoped not active.
AM FEINSTEN: Context interface javax.enterprise.context.RequestScoped not active.
FEIN: execution: 25424/25424

FEIN: Before phase: RESTORE_VIEW 1
FEIN: After phase: RESTORE_VIEW 1
FEIN: Before phase: RENDER_RESPONSE 6
FEIN: After phase: RENDER_RESPONSE 6

AM FEINSTEN: Trying to load class with current thread context classloader: erp.model.orders.Order
AM FEINSTEN: Trying to load class with current thread context classloader: erp.model.orders.Order
FEIN: execution result: order = Order [status=OrderStatus [name=VERIFYING, description=Order verifying, toString()=AbstractEntity [id=2, version=1, createdOn=Sun May 20 21:41:31 CEST 2012, modifiedOn=Sun May 20 21:41:31 CEST 2012]], orderLines={IndirectList: not instantiated}, customer=…, payment=Payment [transactionId=0, status=SUCCESS, remoteStatus=null, method=PaymentMethod [name=INVOICE, description=per invoice, toString()=AbstractEntity [id=9, version=1, createdOn=Sun May 20 21:41:31 CEST 2012, modifiedOn=Sun May 20 21:41:31 CEST 2012]], amount=2, currencyCode=e, toString()=AbstractEntity [id=52, version=1, createdOn=Sat May 26 11:59:23 CEST 2012, modifiedOn=Sat May 26 11:59:23 CEST 2012]], toString()=AbstractEntity [id=51, version=12, createdOn=Sat May 26 11:59:23 CEST 2012, modifiedOn=Sat May 26 15:49:56 CEST 2012]]

SCHWERWIEGEND: No valid EE environment for injection of org.activiti.cdi.impl.context.DefaultBusinessProcessAssociationManager
AM FEINSTEN: Context interface javax.enterprise.context.ConversationScoped not active.
AM FEINSTEN: Context interface javax.enterprise.context.RequestScoped not active.
FEIN: Leaving activity 'setOrderToVerifying'
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerEnd@1d13cb2 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerEnd@1d13cb2 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionDestroyScope@1e80064 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerTake@71b9b3 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
FEIN: ProcessInstance[25424] takes transition (setOrderToVerifying)–flow25–>(checkPaymentMethod)
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionCreateScope@18ec8a3 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerStart@1165270 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerStart@1165270 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationActivityExecute@1349d88 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
FEIN: ProcessInstance[25424] executes Activity(checkPaymentMethod): org.activiti.engine.impl.bpmn.behavior.ServiceTaskDelegateExpressionActivityBehavior
SCHWERWIEGEND: No valid EE environment for injection of org.activiti.cdi.impl.context.DefaultBusinessProcessAssociationManager
AM FEINSTEN: Context interface javax.enterprise.context.ConversationScoped not active.
AM FEINSTEN: Context interface javax.enterprise.context.RequestScoped not active.
FEIN: execution: 25424/25424
AM FEINSTEN: Trying to load class with current thread context classloader: erp.model.orders.Order
FEIN: execution result: orderAlreadyPayed = false
AM FEINSTEN: Trying to load class with current thread context classloader: erp.model.orders.Order
FEIN: execution result: order = Order [status=OrderStatus [name=VERIFYING, description=Order verifying, toString()=AbstractEntity [id=2, version=1, createdOn=Sun May 20 21:41:31 CEST 2012, modifiedOn=Sun May 20 21:41:31 CEST 2012]], orderLines={IndirectList: not instantiated}, customer=…, payment=Payment [transactionId=0, status=SUCCESS, remoteStatus=null, method=PaymentMethod [name=INVOICE, description=per invoice, toString()=AbstractEntity [id=9, version=1, createdOn=Sun May 20 21:41:31 CEST 2012, modifiedOn=Sun May 20 21:41:31 CEST 2012]], amount=2, currencyCode=e, toString()=AbstractEntity [id=52, version=1, createdOn=Sat May 26 11:59:23 CEST 2012, modifiedOn=Sat May 26 11:59:23 CEST 2012]], toString()=AbstractEntity [id=51, version=12, createdOn=Sat May 26 11:59:23 CEST 2012, modifiedOn=Sat May 26 15:49:56 CEST 2012]]
SCHWERWIEGEND: No valid EE environment for injection of org.activiti.cdi.impl.context.DefaultBusinessProcessAssociationManager
AM FEINSTEN: Context interface javax.enterprise.context.ConversationScoped not active.
AM FEINSTEN: Context interface javax.enterprise.context.RequestScoped not active.
FEIN: Leaving activity 'checkPaymentMethod'
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerEnd@1d13cb2 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerEnd@1d13cb2 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionDestroyScope@1e80064 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerTake@71b9b3 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
FEIN: ProcessInstance[25424] takes transition (checkPaymentMethod)–flow3–>(exclusivegateway1)
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionCreateScope@18ec8a3 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerStart@1165270 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerStart@1165270 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationActivityExecute@1349d88 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
FEIN: ProcessInstance[25424] executes Activity(exclusivegateway1): org.activiti.engine.impl.bpmn.behavior.ExclusiveGatewayActivityBehavior
FEIN: Leaving activity 'exclusivegateway1'
SCHWERWIEGEND: No valid EE environment for injection of org.activiti.cdi.impl.context.DefaultBusinessProcessAssociationManager
AM FEINSTEN: Context interface javax.enterprise.context.ConversationScoped not active.
AM FEINSTEN: Context interface javax.enterprise.context.RequestScoped not active.
SCHWERWIEGEND: No valid EE environment for injection of org.activiti.cdi.impl.context.DefaultBusinessProcessAssociationManager
AM FEINSTEN: Context interface javax.enterprise.context.ConversationScoped not active.
AM FEINSTEN: Context interface javax.enterprise.context.RequestScoped not active.
FEIN: Sequence flow 'flow9 'selected as outgoing sequence flow.
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerEnd@1d13cb2 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerEnd@1d13cb2 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionDestroyScope@1e80064 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerTake@71b9b3 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
FEIN: ProcessInstance[25424] takes transition (exclusivegateway1)–flow9–>(verifyPaymentData)
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionCreateScope@18ec8a3 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerStart@1165270 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerStart@1165270 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
AM FEINSTEN: AtomicOperation: org.activiti.engine.impl.pvm.runtime.AtomicOperationActivityExecute@1349d88 on org.activiti.engine.impl.interceptor.CommandContext@14e4ce7
FEIN: ProcessInstance[25424] executes Activity(verifyPaymentData): org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior
SCHWERWIEGEND: No valid EE environment for injection of org.activiti.cdi.impl.context.DefaultBusinessProcessAssociationManager
AM FEINSTEN: Context interface javax.enterprise.context.ConversationScoped not active.
AM FEINSTEN: Context interface javax.enterprise.context.RequestScoped not active.
WARNUNG: Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '2' for key 'PRIMARY'
Error Code: 1062
Call: INSERT INTO ERP_ORDERSTATUS (ID, CREATEDON, DESCRIPTION, MODIFIEDON, NAME, VERSION) VALUES (?, ?, ?, ?, ?, ?)
   bind => [6 parameters bound]
Query: WriteObjectQuery(OrderStatus [name=VERIFYING, description=Order verifying, toString()=AbstractEntity [id=2, version=1, createdOn=Sun May 20 21:41:31 CEST 2012, modifiedOn=Sun May 20 21:41:31 CEST 2012]])
   at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
   at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:840)
   at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:906)
   at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:592)
   at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:535)
   at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1717)
   at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:253)
   at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:207)
   at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:193)
   at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:342)
   at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:162)
   at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:177)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:472)
   at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80)
   at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.performUserDefinedWrite(DatabaseQueryMechanism.java:564)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.performUserDefinedInsert(DatabaseQueryMechanism.java:532)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:402)
   at org.eclipse.persistence.queries.WriteObjectQuery.executeCommitWithChangeSet(WriteObjectQuery.java:121)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:287)
   at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
   at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
   at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:743)
   at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108)
   at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85)
   at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1449)
   at org.eclipse.persistence.mappings.ObjectReferenceMapping.update(ObjectReferenceMapping.java:1156)
   at org.eclipse.persistence.mappings.ObjectReferenceMapping.preUpdate(ObjectReferenceMapping.java:591)
   at org.eclipse.persistence.descriptors.DescriptorQueryManager.preUpdate(DescriptorQueryManager.java:1109)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.updateObjectForWriteWithChangeSet(DatabaseQueryMechanism.java:1004)
   at org.eclipse.persistence.queries.UpdateObjectQuery.executeCommitWithChangeSet(UpdateObjectQuery.java:84)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:287)
   at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
   at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
   at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:743)
   at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108)
   at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85)
   at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1449)
   at org.eclipse.persistence.internal.sessions.CommitManager.commitChangedObjectsForClassWithChangeSet(CommitManager.java:265)
   at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:128)
   at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:3799)
   at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1415)
   at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitToDatabase(RepeatableWriteUnitOfWork.java:636)
   at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithPreBuiltChangeSet(UnitOfWorkImpl.java:1561)
   at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.writeChanges(RepeatableWriteUnitOfWork.java:447)
   at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:780)
   at org.activiti.engine.impl.variable.EntityManagerSessionImpl.flush(EntityManagerSessionImpl.java:54)
   at org.activiti.engine.impl.interceptor.CommandContext.flushSessions(CommandContext.java:149)
   at org.activiti.engine.impl.interceptor.CommandContext.close(CommandContext.java:105)
   at org.activiti.engine.impl.interceptor.CommandContextInterceptor.execute(CommandContextInterceptor.java:49)
   at org.activiti.engine.impl.interceptor.JtaTransactionInterceptor.execute(JtaTransactionInterceptor.java:59)
   at org.activiti.engine.impl.interceptor.LogInterceptor.execute(LogInterceptor.java:33)
   at org.activiti.engine.impl.jobexecutor.ExecuteJobsRunnable.run(ExecuteJobsRunnable.java:46)
   at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
   at java.lang.Thread.run(Thread.java:662)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '2' for key 'PRIMARY'
   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
   at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
   at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
   at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
   at com.mysql.jdbc.Util.getInstance(Util.java:386)
   at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1039)
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3597)
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3529)
   at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1990)
   at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2151)
   at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2625)
   at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2333)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2318)
   at com.mysql.jdbc.jdbc2.optional.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:875)
   at com.sun.gjc.spi.base.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:125)
   at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:831)
   … 60 more

SCHWERWIEGEND: Error while closing command context
org.activiti.engine.ActivitiException: Error while flushing EntityManager: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '2' for key 'PRIMARY'
Error Code: 1062
Call: INSERT INTO ERP_ORDERSTATUS (ID, CREATEDON, DESCRIPTION, MODIFIEDON, NAME, VERSION) VALUES (?, ?, ?, ?, ?, ?)
   bind => [6 parameters bound]
Query: WriteObjectQuery(OrderStatus [name=VERIFYING, description=Order verifying, toString()=AbstractEntity [id=2, version=1, createdOn=Sun May 20 21:41:31 CEST 2012, modifiedOn=Sun May 20 21:41:31 CEST 2012]])
   at org.activiti.engine.impl.variable.EntityManagerSessionImpl.flush(EntityManagerSessionImpl.java:60)
   at org.activiti.engine.impl.interceptor.CommandContext.flushSessions(CommandContext.java:149)
   at org.activiti.engine.impl.interceptor.CommandContext.close(CommandContext.java:105)
   at org.activiti.engine.impl.interceptor.CommandContextInterceptor.execute(CommandContextInterceptor.java:49)
   at org.activiti.engine.impl.interceptor.JtaTransactionInterceptor.execute(JtaTransactionInterceptor.java:59)
   at org.activiti.engine.impl.interceptor.LogInterceptor.execute(LogInterceptor.java:33)
   at org.activiti.engine.impl.jobexecutor.ExecuteJobsRunnable.run(ExecuteJobsRunnable.java:46)
   at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
   at java.lang.Thread.run(Thread.java:662)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '2' for key 'PRIMARY'
Error Code: 1062
Call: INSERT INTO ERP_ORDERSTATUS (ID, CREATEDON, DESCRIPTION, MODIFIEDON, NAME, VERSION) VALUES (?, ?, ?, ?, ?, ?)
   bind => [6 parameters bound]
Query: WriteObjectQuery(OrderStatus [name=VERIFYING, description=Order verifying, toString()=AbstractEntity [id=2, version=1, createdOn=Sun May 20 21:41:31 CEST 2012, modifiedOn=Sun May 20 21:41:31 CEST 2012]])
   at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:786)
   at org.activiti.engine.impl.variable.EntityManagerSessionImpl.flush(EntityManagerSessionImpl.java:54)
   … 9 more
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '2' for key 'PRIMARY'
Error Code: 1062
Call: INSERT INTO ERP_ORDERSTATUS (ID, CREATEDON, DESCRIPTION, MODIFIEDON, NAME, VERSION) VALUES (?, ?, ?, ?, ?, ?)
   bind => [6 parameters bound]
Query: WriteObjectQuery(OrderStatus [name=VERIFYING, description=Order verifying, toString()=AbstractEntity [id=2, version=1, createdOn=Sun May 20 21:41:31 CEST 2012, modifiedOn=Sun May 20 21:41:31 CEST 2012]])
   at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
   at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:840)
   at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:906)
   at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:592)
   at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:535)
   at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1717)
   at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:253)
   at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:207)
   at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:193)
   at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:342)
   at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:162)
   at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:177)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:472)
   at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80)
   at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.performUserDefinedWrite(DatabaseQueryMechanism.java:564)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.performUserDefinedInsert(DatabaseQueryMechanism.java:532)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:402)
   at org.eclipse.persistence.queries.WriteObjectQuery.executeCommitWithChangeSet(WriteObjectQuery.java:121)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:287)
   at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
   at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
   at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:743)
   at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108)
   at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85)
   at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1449)
   at org.eclipse.persistence.mappings.ObjectReferenceMapping.update(ObjectReferenceMapping.java:1156)
   at org.eclipse.persistence.mappings.ObjectReferenceMapping.preUpdate(ObjectReferenceMapping.java:591)
   at org.eclipse.persistence.descriptors.DescriptorQueryManager.preUpdate(DescriptorQueryManager.java:1109)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.updateObjectForWriteWithChangeSet(DatabaseQueryMechanism.java:1004)
   at org.eclipse.persistence.queries.UpdateObjectQuery.executeCommitWithChangeSet(UpdateObjectQuery.java:84)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:287)
   at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
   at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
   at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:743)
   at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108)
   at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85)
   at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1449)
   at org.eclipse.persistence.internal.sessions.CommitManager.commitChangedObjectsForClassWithChangeSet(CommitManager.java:265)
   at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:128)
   at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:3799)
   at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1415)
   at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitToDatabase(RepeatableWriteUnitOfWork.java:636)
   at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithPreBuiltChangeSet(UnitOfWorkImpl.java:1561)
   at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.writeChanges(RepeatableWriteUnitOfWork.java:447)
   at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:780)
   … 10 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '2' for key 'PRIMARY'
   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
   at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
   at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
   at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
   at com.mysql.jdbc.Util.getInstance(Util.java:386)
   at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1039)
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3597)
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3529)
   at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1990)
   at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2151)
   at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2625)
   at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2333)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2318)
   at com.mysql.jdbc.jdbc2.optional.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:875)
   at com.sun.gjc.spi.base.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:125)
   at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:831)
   … 60 more

FEIN: firing event rolling back…
FEIN: rolling back ibatis sql session…
FEIN: firing event rolled back…
FEIN: — ExecuteJobsCmd finished ——————————————————–

SCHWERWIEGEND: Exception in thread "pool-16-thread-1"
SCHWERWIEGEND: org.activiti.engine.ActivitiException: Error while flushing EntityManager: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '2' for key 'PRIMARY'
Error Code: 1062
Call: INSERT INTO ERP_ORDERSTATUS (ID, CREATEDON, DESCRIPTION, MODIFIEDON, NAME, VERSION) VALUES (?, ?, ?, ?, ?, ?)
   bind => [6 parameters bound]
Query: WriteObjectQuery(OrderStatus [name=VERIFYING, description=Order verifying, toString()=AbstractEntity [id=2, version=1, createdOn=Sun May 20 21:41:31 CEST 2012, modifiedOn=Sun May 20 21:41:31 CEST 2012]])
   at org.activiti.engine.impl.variable.EntityManagerSessionImpl.flush(EntityManagerSessionImpl.java:60)
   at org.activiti.engine.impl.interceptor.CommandContext.flushSessions(CommandContext.java:149)
   at org.activiti.engine.impl.interceptor.CommandContext.close(CommandContext.java:105)
   at org.activiti.engine.impl.interceptor.CommandContextInterceptor.execute(CommandContextInterceptor.java:49)
   at org.activiti.engine.impl.interceptor.JtaTransactionInterceptor.execute(JtaTransactionInterceptor.java:59)
   at org.activiti.engine.impl.interceptor.LogInterceptor.execute(LogInterceptor.java:33)
   at org.activiti.engine.impl.jobexecutor.ExecuteJobsRunnable.run(ExecuteJobsRunnable.java:46)
   at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
   at java.lang.Thread.run(Thread.java:662)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '2' for key 'PRIMARY'
Error Code: 1062
Call: INSERT INTO ERP_ORDERSTATUS (ID, CREATEDON, DESCRIPTION, MODIFIEDON, NAME, VERSION) VALUES (?, ?, ?, ?, ?, ?)
   bind => [6 parameters bound]
Query: WriteObjectQuery(OrderStatus [name=VERIFYING, description=Order verifying, toString()=AbstractEntity [id=2, version=1, createdOn=Sun May 20 21:41:31 CEST 2012, modifiedOn=Sun May 20 21:41:31 CEST 2012]])
   at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:786)
   at org.activiti.engine.impl.variable.EntityManagerSessionImpl.flush(EntityManagerSessionImpl.java:54)
   … 9 more
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '2' for key 'PRIMARY'
Error Code: 1062
Call: INSERT INTO ERP_ORDERSTATUS (ID, CREATEDON, DESCRIPTION, MODIFIEDON, NAME, VERSION) VALUES (?, ?, ?, ?, ?, ?)
   bind => [6 parameters bound]
Query: WriteObjectQuery(OrderStatus [name=VERIFYING, description=Order verifying, toString()=AbstractEntity [id=2, version=1, createdOn=Sun May 20 21:41:31 CEST 2012, modifiedOn=Sun May 20 21:41:31 CEST 2012]])
   at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
   at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:840)
   at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:906)
   at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:592)
   at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:535)
   at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1717)
   at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:253)
   at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:207)
   at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:193)
   at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:342)
   at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:162)
   at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:177)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:472)
   at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80)
   at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.performUserDefinedWrite(DatabaseQueryMechanism.java:564)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.performUserDefinedInsert(DatabaseQueryMechanism.java:532)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:402)
   at org.eclipse.persistence.queries.WriteObjectQuery.executeCommitWithChangeSet(WriteObjectQuery.java:121)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:287)
   at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
   at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
   at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:743)
   at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108)
   at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85)
   at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1449)
   at org.eclipse.persistence.mappings.ObjectReferenceMapping.update(ObjectReferenceMapping.java:1156)
   at org.eclipse.persistence.mappings.ObjectReferenceMapping.preUpdate(ObjectReferenceMapping.java:591)
   at org.eclipse.persistence.descriptors.DescriptorQueryManager.preUpdate(DescriptorQueryManager.java:1109)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.updateObjectForWriteWithChangeSet(DatabaseQueryMechanism.java:1004)
   at org.eclipse.persistence.queries.UpdateObjectQuery.executeCommitWithChangeSet(UpdateObjectQuery.java:84)
   at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:287)
   at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
   at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
   at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:743)
   at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108)
   at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85)
   at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
   at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1449)
   at org.eclipse.persistence.internal.sessions.CommitManager.commitChangedObjectsForClassWithChangeSet(CommitManager.java:265)
   at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:128)
   at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:3799)
   at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1415)
   at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitToDatabase(RepeatableWriteUnitOfWork.java:636)
   at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithPreBuiltChangeSet(UnitOfWorkImpl.java:1561)
   at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.writeChanges(RepeatableWriteUnitOfWork.java:447)
   at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:780)
   … 10 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '2' for key 'PRIMARY'
   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
   at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
   at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
   at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
   at com.mysql.jdbc.Util.getInstance(Util.java:386)
   at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1039)
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3597)
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3529)
   at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1990)
   at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2151)
   at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2625)
   at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2333)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2318)
   at com.mysql.jdbc.jdbc2.optional.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:875)
   at com.sun.gjc.spi.base.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:125)
   at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:831)
   … 60 more
5 REPLIES 5

frederikherema1
Star Contributor
Star Contributor
Hi,

When using JPA inside Activiti there are two ways of wiring in the EntityManager (http://activiti.org/userguide/index.html#jpaconfiguration). The fist on is using the persistence-unit name. If this value is set,
interceptors are added to the stack, which flush the entity manager every time an activity operation ends (e.g.. startProcess, completeTask). The entity manager is obtained using the default way, using the persistence-unit name (EntityManagerFactory).

Another option is to pass in a reference to your (potentially managed) EntityManagerFactory, instead of the PU-name. This way, not a default EntityManager will be used, but one that is aware of your environment/app.

I'd recommend using the second approach, wiring in your entityManagerFactory. Make sure, in case the entityManager is "managed", you set the "jpaCloseEntityManager" and "jpaHandleTransaction" properties to false. In that case, the closing/comitting will be done by your services wrapping activiti-calls, rather than in activiti-calls itself.

chris_joelly
Champ in-the-making
Champ in-the-making
Hi,

thank u for your answer. As u saw in my activiti.cfg.xml i used the first option, setting the JPA persistence unit name.

I tried to change to the second approach, and defined the persistence-unit-ref in the web.xml so i can access it via JNDI. I can access it via java:comp/env, this works fine when i perform the lookup from within an EJB. At the moment the EMF is injected into Activiti i can not access the name space java:comp/env and so i can not wire in the EntityManagerFactory.

<jee:jndi-lookup id="entityManagerFactory" jndi-name="java:comp/env/persistence/erpEMF" lookup-on-startup="false" proxy-interface="javax.persistence.EntityManagerFactory"/>

<bean id="processEngineConfiguration"
class="org.activiti.cdi.CdiJtaProcessEngineConfiguration">
<property name="jpaEntityManagerFactory" ref="entityManagerFactory" />

does not work from the Spring based Activiti initialisation.

I never used Spring before (Activiti) and so i am relatively new to the Spring world. I implemented a proxy for the EntityManagerFactory which pulls one from JNDI if the proxy methods are accessed, and there i saw that in this execution context i can not access java:comp/env.


<bean id="entityManagerFactory" class="erp.domain.activiti.mgnt.EMFProxy">
<property name="jndiName" value="java:comp/env/persistence/erpEMF" />
</bean>

<bean id="processEngineConfiguration"
class="org.activiti.cdi.CdiJtaProcessEngineConfiguration">
<property name="jpaEntityManagerFactory" ref="entityManagerFactory" />



FEIN: Start with context: 'java:comp/env'
SCHWERWIEGEND: Error dumping JNDI tree
javax.naming.NamingException: Lookup failed for 'java:comp/env' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NamingException: Invocation exception: Got null ComponentInvocation ]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:518)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at erp.domain.activiti.mgnt.JNDITreeDumper.dumpJndiTree(JNDITreeDumper.java:33)
at erp.domain.activiti.mgnt.EMFProxy.initialiseEMF(EMFProxy.java:104)
at erp.domain.activiti.mgnt.EMFProxy.createEntityManager(EMFProxy.java:44)
at org.activiti.engine.impl.variable.EntityManagerSessionImpl.getEntityManager(EntityManagerSessionImpl.java:84)
at org.activiti.engine.impl.variable.JPAEntityMappings.findEntity(JPAEntityMappings.java:123)
at org.activiti.engine.impl.variable.JPAEntityMappings.getJPAEntity(JPAEntityMappings.java:119)
at org.activiti.engine.impl.variable.JPAEntityVariableType.getValue(JPAEntityVariableType.java:77)
at org.activiti.engine.impl.persistence.entity.VariableInstanceEntity.getValue(VariableInstanceEntity.java:158)
at org.activiti.engine.impl.persistence.entity.VariableScopeImpl.getVariable(VariableScopeImpl.java:93)
at org.activiti.engine.impl.bpmn.behavior.CallActivityBehavior.execute(CallActivityBehavior.java:79)

To verify this behavior i wrote an JNDI tree dumper which i use from a @Singleton @Startup EJB and from the EMF proxy. When it is accessed in the context of the EMF proxy when Activiti tries to get an EntityManager from the EMF proxy i can not access the JNDI name space java:comp/env, thus i can not access the provided EMF from the application server.

I tried in two app servers, Glassfish 3.1.2 and JBoss AS 7.1.1, both show me the same behavior.

I dont know how i can wire in the EntityManagerFactory from my app server using Spring, it seems there is something wrong with my concept of the app architecture. I read lots of spec docs last days but it seems java:comp/env resources are not meant to be visible in a context outside an JEE module, but i dont understand why the Spring based Activiti initialization phase happens outside the webapp/war context. And i tried to get the EMF to the "global" context just like the data source which can be looked up via JNDI, but this seem to be not possible soley through deployment descriptors.

Anyway, after all this mess i will finish my day with lots of beer Smiley Happy

Thanks anyway,

Chris

chris_joelly
Champ in-the-making
Champ in-the-making
it seems that i found the reason why i can not inject a EntityManagerFactory which is looked up using JNDI using activiti.cfg.xml when Activiti is initialized. I use activiti-cdi to "boot" the process engine and during that phase Activiti is initialized using the Spring style config mechanism. In that mechanism i used <jee:jndi-lookup…/> to get an EMF and inject it to Activiti so that Activiti is able to use the same persistence unit which is used throughout the rest of the app.

But when Activiti is initialized by the WeldDeployer there is no java:comp/env JNDI name space available, so it is not possible to use the JNDI component environment during that phase. And, furthermore, if i postpone the JNDI lookup with <jee:jndi-lookup… lookup-on-startup="false" proxy-interface="javax.persistence.EntityManagerFactory"/> so that the complete webapp is initialized first before Activiti tries to access the EMF then the JNDI lookup to java:comp/env does not work either, Activiti does not see this JNDI context. And when Activiti executes a timer event, java:comp/env is not available too.

So, when activiti-cdi is used, only global JNDI resources can be used, as it works with a datasource for example which can be found at jdbc:… and not below java:comp/env…. The component environment, e.g. via a persistence-unit-ref in web.xml, is not usable with activiti-cdi. At least i dont know how to do it Smiley Happy

p4w3l
Champ in-the-making
Champ in-the-making
It seems I've fallen into the same trap. After few hours of experiment the following helped:

upgrade EclipseLink from 2.3.3 -> 2.4.1

It is "green" and not tested remedium. I am just happy to share it with you! I never upgraded underlying EL so I cannt figure all the side effects. I will share more results after testings.

p4w3l
Champ in-the-making
Champ in-the-making
The reason I post here is that I see some similarities with initial post:

- EclipseLink 2.3.3
- production quality set of JPA libraries that works fine just with one exception:

When my CDI @BusinessProcess @Observes @EndActivity tries to modify JPA process attached entity - the flush exception is raised. It happens in the following conditions:

- the whole CDI method is succesfully executed ( JPA data change is commited )
- the flush exception is in taskService.complete(…) after CDI method is done
- the related entity must be modified. Modifing only scalar values of JPA variable doesn't raise the flush exception.

Simply upgrade from EclipseLink 2.3.3 to 2.4.1 solves the problem.