Activiti7 study notes-basic introduction and use of activiti

1. Activiti use environment

1. Installation of idea actiBPM plug-in

Method 1
Search for actiBPM through idea to install the plug-in.

Insert picture description here


Method 2 Go to the
official website to find the actiBPM plug-in and download the plug-in. Install the plug-in as shown in the figure.

Insert picture description here

2. Activiti required environment deployment

1) Create a maven project and add various jar packages required by activiti in the pom.xml file

activiti-engine-7.0.0.beta1.jar

Jar packages that activiti depends on: mybatis, alf4j, log4j, etc.

Spring packages that activiti depends on

mysql database driver (database driver can be changed according to your own needs, please refer to the database supported by activiti for details)

Third-party data connection pool dbcp

Unit test Junit-4.12.jar (use activiti for testing)

<properties>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <activiti.version>7.0.0.Beta1</activiti.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.activiti</groupId>
        <artifactId>activiti-engine</artifactId>
        <version>${activiti.version}</version>
    </dependency>
    <dependency>
        <groupId>org.activiti</groupId>
        <artifactId>activiti-spring</artifactId>
        <version>${activiti.version}</version>
    </dependency>
    <!-- bpmn 模型处理 -->
    <dependency>
        <groupId>org.activiti</groupId>
        <artifactId>activiti-bpmn-model</artifactId>
        <version>${activiti.version}</version>
    </dependency>
    <!-- bpmn 转换 -->
    <dependency>
        <groupId>org.activiti</groupId>
        <artifactId>activiti-bpmn-converter</artifactId>
        <version>${activiti.version}</version>
    </dependency>
    <!-- bpmn json数据转换 -->
    <dependency>
        <groupId>org.activiti</groupId>
        <artifactId>activiti-json-converter</artifactId>
        <version>${activiti.version}</version>
    </dependency>
    <!-- bpmn 布局 -->
    <dependency>
        <groupId>org.activiti</groupId>
        <artifactId>activiti-bpmn-layout</artifactId>
        <version>${activiti.version}</version>
    </dependency>
    <!-- activiti 云支持 -->
    <dependency>
        <groupId>org.activiti.cloud</groupId>
        <artifactId>activiti-cloud-services-api</artifactId>
        <version>${activiti.version}</version>
    </dependency>
    <!-- mysql驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.40</version>
    </dependency>
    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>
    <!-- 链接池 -->
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <!-- log start -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
</dependencies>

2) Create log files and configuration files required by activiti in the resources folder

activiti.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/contex
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 默认id对应的值 为processEngineConfiguration -->
    <!-- processEngine Activiti的流程引擎 -->
    <bean id="processEngineConfiguration"
          class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration">
        <property name="jdbcDriver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///activititest?characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=UTC&amp;allowPublicKeyRetrieval=true"/>
        <property name="jdbcUsername" value="root"/>
        <property name="jdbcPassword" value="123456"/>
        <!-- activiti数据库表处理策略 -->
        <property name="databaseSchemaUpdate" value="true"/>
    </bean>
    <!-- 这里可以使用 链接池 dbcp-->
<!--    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">-->
<!--        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />-->
<!--        <property name="url" value="jdbc:mysql:///activititest" />-->
<!--        <property name="username" value="root" />-->
<!--        <property name="password" value="123456" />-->
<!--        <property name="maxActive" value="3" />-->
<!--        <property name="maxIdle" value="1" />-->
<!--    </bean>-->
<!--    <bean id="processEngineConfiguration"-->
<!--          class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration">-->
<!--        &lt;!&ndash; 引用数据源 上面已经设置好了&ndash;&gt;-->
<!--        <property name="dataSource" ref="dataSource" />-->
<!--        &lt;!&ndash; activiti数据库表处理策略 &ndash;&gt;-->
<!--        <property name="databaseSchemaUpdate" value="true"/>-->
<!--    </bean>-->
</beans>

Log file log4j.properties

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r[%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=f:\act\activiti.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r[%15.15t] %-5p %30.30c %x - %m\n

3. Automatic deployment of Activiti database tables

Execute the following code activiti to automatically help you create a table for controlling the workflow. A total of 25 photos.

    /**
     * 生成 activiti的数据库表
     */
    @Test
    public void testCreateDbTable() {
        //使用classpath下的activiti.cfg.xml中的配置创建processEngine
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
    }
Insert picture description here

Second, the meaning of each table in Activiti

Table classificationTable NameExplanation
General data
[ACT_GE_BYTEARRAY]General process definition and process resources
[ACT_GE_PROPERTY]System related attributes
Process history
[ACT_HI_ACTINST]Historical process examples
[ACT_HI_ATTACHMENT]Historical process attachment
[ACT_HI_COMMENT]Historical descriptive information
[ACT_HI_DETAIL]Detailed information in the historical process operation
[ACT_HI_IDENTITYLINK]User relationship during historical process operation
[ACT_HI_PROCINST]Historical process examples
[ACT_HI_TASKINST]Historical mission examples
[ACT_HI_VARINST]Variable information in historical process running
Process definition table
[ACT_RE_DEPLOYMENT]Deployment unit information
[ACT_RE_MODEL]Model information
[ACT_RE_PROCDEF]Deployed process definition
Run instance table
[ACT_RU_EVENT_SUBSCR]Runtime events
[ACT_RU_EXECUTION]Runtime process execution example
[ACT_RU_IDENTITYLINK]User relationship information at runtime, storing information about task nodes and participants
[ACT_RU_JOB]Runtime job
[ACT_RU_TASK]Runtime task
[ACT_RU_VARIABLE]Runtime variable table

Three, the process symbol of activiti

BPMN 2.0 is the abbreviation of Business Process Modeling Notation 2.0.

Insert picture description here


reference

4. Draw and deploy the execution process by using the Idea plug-in.

1. Draw bpmn

1) Create a bpmn file, and draw a bpmn flowchart through the plug-in (which can be converted to an xml file and a png file).

Insert picture description here


Click to open the bpmn file as shown below

![


Insert picture description here)(https://img-blog.csdnimg.cn/20210605161837578.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzH70_FF_color=FF_lb_lb_16hZ2

Simple drawing workflow, as shown in the figure below

Insert picture description here


2) Change the extension of the file to .xml, as shown below

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:tns="http://www.activiti.org/testm1622878134337" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" expressionLanguage="http://www.w3.org/1999/XPath" id="m1622878134337" name="" targetNamespace="http://www.activiti.org/testm1622878134337" typeLanguage="http://www.w3.org/2001/XMLSchema">
  <process id="myFlow01" isClosed="false" isExecutable="true" processType="None">
    <startEvent id="start1" name="StartEvent"/>
    <userTask activiti:assignee="操作员01" activiti:candidateUsers="候选人01" activiti:exclusive="true" id="flow01" name="发送请假申请"/>
    <userTask activiti:assignee="操作员02" activiti:candidateUsers="候选人02" activiti:exclusive="true" id="flow02" name="主管审批"/>
    <endEvent id="end1" name="EndEvent"/>
    <sequenceFlow id="_6" sourceRef="start1" targetRef="flow01"/>
    <sequenceFlow id="_7" sourceRef="flow01" targetRef="flow02"/>
    <sequenceFlow id="_8" sourceRef="flow02" targetRef="end1"/>
  </process>
  <bpmndi:BPMNDiagram documentation="background=#FFFFFF;count=1;horizontalcount=1;orientation=0;width=842.4;height=1195.2;imageableWidth=832.4;imageableHeight=1185.2;imageableX=5.0;imageableY=5.0" id="Diagram-_1" name="New Diagram">
    <bpmndi:BPMNPlane bpmnElement="myFlow01">
      <bpmndi:BPMNShape bpmnElement="start1" id="Shape-start1">
        <dc:Bounds height="32.0" width="32.0" x="310.0" y="85.0"/>
        <bpmndi:BPMNLabel>
          <dc:Bounds height="32.0" width="32.0" x="0.0" y="0.0"/>
        </bpmndi:BPMNLabel>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="flow01" id="Shape-flow01">
        <dc:Bounds height="55.0" width="85.0" x="285.0" y="165.0"/>
        <bpmndi:BPMNLabel>
          <dc:Bounds height="55.0" width="85.0" x="0.0" y="0.0"/>
        </bpmndi:BPMNLabel>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="flow02" id="Shape-flow02">
        <dc:Bounds height="55.0" width="85.0" x="285.0" y="260.0"/>
        <bpmndi:BPMNLabel>
          <dc:Bounds height="55.0" width="85.0" x="0.0" y="0.0"/>
        </bpmndi:BPMNLabel>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="end1" id="Shape-end1">
        <dc:Bounds height="32.0" width="32.0" x="310.0" y="360.0"/>
        <bpmndi:BPMNLabel>
          <dc:Bounds height="32.0" width="32.0" x="0.0" y="0.0"/>
        </bpmndi:BPMNLabel>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="_6" id="BPMNEdge__6" sourceElement="_2" targetElement="_3">
        <di:waypoint x="326.0" y="117.0"/>
        <di:waypoint x="326.0" y="165.0"/>
        <bpmndi:BPMNLabel>
          <dc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        </bpmndi:BPMNLabel>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_7" id="BPMNEdge__7" sourceElement="_3" targetElement="_4">
        <di:waypoint x="327.5" y="220.0"/>
        <di:waypoint x="327.5" y="260.0"/>
        <bpmndi:BPMNLabel>
          <dc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        </bpmndi:BPMNLabel>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_8" id="BPMNEdge__8" sourceElement="_4" targetElement="_5">
        <di:waypoint x="326.0" y="315.0"/>
        <di:waypoint x="326.0" y="360.0"/>
        <bpmndi:BPMNLabel>
          <dc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        </bpmndi:BPMNLabel>
      </bpmndi:BPMNEdge>
    </bpmndi:BPMNPlane>
  </bpmndi:BPMNDiagram>
</definitions>

3) To convert to a picture, you need to convert it to an xml file first. You can convert it to a picture through the following operations as shown in the figure. If there is no Diagrams, you can refer to the idea actiBPM plug-in to generate a png file (to solve the problem of not having Diagrams or Designer options)

Insert picture description here


Insert picture description here

2. Execute the workflow

1) Deployment process definition

    /**
     * 部署流程定义
     */
    @Test
    public void testDeployment(){
//        1、创建ProcessEngine
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        2、得到RepositoryService实例
        RepositoryService repositoryService = processEngine.getRepositoryService();
//        3、使用RepositoryService进行部署
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("bpmn/myFlow01.bpmn") // 添加bpmn资源
                .addClasspathResource("bpmn/myFlow01.xml")  // 添加xml资源
                .addClasspathResource("bpmn/myFlow01.png")  // 添加png资源
                .name("请假申请流程01")
                .deploy();
//        4、输出部署信息
        System.out.println("流程部署id:" + deployment.getId());
        System.out.println("流程部署名称:" + deployment.getName());
    }

Execution results

Insert picture description here


Database table changes
The three tables for operating activiti after the process definition is deployed are as follows:

act_re_deployment process definition deployment table, add a record for each deployment

Insert picture description here

act_re_procdef process definition table, the deployment of each new process definition will add a record to this table

Insert picture description here

act_ge_bytearray Process resource table

Insert picture description here


2) Start process instance

    /**
     * 启动流程实例
     */
    @Test
    public void testStartProcess(){
//        1、创建ProcessEngine
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        2、获取RunTimeService
        RuntimeService runtimeService = processEngine.getRuntimeService();
//        3、根据流程定义Id启动流程
        ProcessInstance processInstance = runtimeService
                .startProcessInstanceByKey("myFlow01");
//        输出内容
        System.out.println("流程定义id:" + processInstance.getProcessDefinitionId());
        System.out.println("流程实例id:" + processInstance.getId());
        System.out.println("当前活动Id:" + processInstance.getActivityId());
    }

Operation result

Insert picture description here


database table changes
act_hi_actinst process instance execution history

Insert picture description here

Historical information of participating users in the act_hi_identitylink process

Insert picture description here

act_hi_procinst process instance history information

Insert picture description here

act_hi_taskinst process task history information

Insert picture description here

act_ru_execution process execution information

Insert picture description here

Participating user information of act_ru_identitylink process

Insert picture description here

act_ru_task task information

Insert picture description here


3) complete the task

    /**
     * 完成个人任务
     */
    @Test
    public void completeTask(){
        String ass = "操作员01";

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

        TaskService taskService = processEngine.getTaskService();
        //查询该用户是否有该任务
        Task task = taskService.createTaskQuery().taskAssignee(ass).singleResult();
        //将查询个人任务完成act_ru_task,完成后会将历史记录存在hi表中,当前任务会变成下一个阶段的任务
        if (task == null){
            System.out.println(ass+"没有任务");
        }else
            System.out.println(ass+"完成任务"+task.getName()+"--"+task.getId());
            taskService.complete(task.getId());
    }

Operation result The

Insert picture description here


database changes are basically the same as the start process instance. Add the current process record to the act_hi table, and modify the end time of the previous process, and the information of the current process stage in act_ru is as shown in the figure.
act_ru_task task information

Insert picture description here


act_hi_actinst process instance execution history

Insert picture description here


4) Delete process

    /**
     * 删除流程
     * 1、删除流程定义,如果该流程定义已有流程实例启动则删除时出错(未完成该流程)
     * 2、设置true 级联删除流程定义,即使该流程有流程实例启动也可以删除(未完成的流程实例被删除)
     * act_hi的表是不会被删除的
     * 主要是删除act_ru以及部署时操作的那几张表的相关信息
     */
    @Test
    public void deleteDeployment() {
        // 流程部署id
        String deploymentId = "12501";

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        // 通过流程引擎获取repositoryService
        RepositoryService repositoryService = processEngine
                .getRepositoryService();
        //
        repositoryService.deleteDeployment(deploymentId);
        //设置true 级联删除流程定义,即使该流程有流程实例启动也可以删除
        //repositoryService.deleteDeployment(deploymentId, true);
    }

Running results
Result 1 (using repositoryService.deleteDeployment(deploymentId);):

Insert picture description here


Result 2 (using repositoryService.deleteDeployment(deploymentId, true);):

Insert picture description here


database table changes:
act_re_deployment

Insert picture description here

act_re_procdef

Insert picture description here

act_ge_bytearray

Insert picture description here


Use repositoryService.deleteDeployment(deploymentId);, when the process instance is not completed, the relevant data in the act_ru table is deleted, and the process completion record of act_hi is still
using repositoryService.deleteDeployment(deploymentId, true);, then the associated information is all Deleted, including act_hi

act_ru_task

Insert picture description here


act_ru_identitylink,

Insert picture description here


etc. act_ru and act_hi tables

5) Query of process history information

    /**
     * 查看历史信息
     */
    @Test
    public void findHistoryInfo(){
//      获取引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        获取HistoryService
        HistoryService historyService = processEngine.getHistoryService();
//        获取 actinst表的查询对象
        HistoricActivityInstanceQuery instanceQuery = historyService.createHistoricActivityInstanceQuery();
//        查询 actinst表,条件:根据 InstanceId 查询
//        instanceQuery.processInstanceId("2501");
//        查询 actinst表,条件:根据 DefinitionId 查询
        instanceQuery.processDefinitionId("12501");
//        增加排序操作,orderByHistoricActivityInstanceStartTime 根据开始时间排序 asc 升序
        instanceQuery.orderByHistoricActivityInstanceStartTime().asc();
//        查询所有内容
        List<HistoricActivityInstance> activityInstanceList = instanceQuery.list();
//        输出
        for (HistoricActivityInstance hi : activityInstanceList) {
            System.out.println(hi.getActivityId());
            System.out.println(hi.getActivityName());
            System.out.println(hi.getProcessDefinitionId());
            System.out.println(hi.getProcessInstanceId());
            System.out.println("<==========================>");
        }
    }

6) Download of process resources
needs to introduce the jar package of commons-io

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
    /**
     * 流程资源的下载
     * @throws IOException
     */
    @Test
    public void  queryBpmnFile() throws IOException {
//        1、得到引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        2、获取repositoryService
        RepositoryService repositoryService = processEngine.getRepositoryService();
//        3、得到查询器:ProcessDefinitionQuery,设置查询条件,得到想要的流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey("myFlow01")
                .singleResult();
//        4、通过流程定义信息,得到部署ID
        String deploymentId = processDefinition.getDeploymentId();
//        5、通过repositoryService的方法,实现读取图片信息和bpmn信息
//        png图片的流
        InputStream pngInput = repositoryService.getResourceAsStream(deploymentId, processDefinition.getDiagramResourceName());
//        bpmn文件的流
        InputStream bpmnInput = repositoryService.getResourceAsStream(deploymentId, processDefinition.getResourceName());
//        6、构造OutputStream流
        File file_png = new File("d:/flow01.png");
        File file_bpmn = new File("d:/flow01.bpmn");
        FileOutputStream bpmnOut = new FileOutputStream(file_bpmn);
        FileOutputStream pngOut = new FileOutputStream(file_png);
//        7、输入流,输出流的转换
        IOUtils.copy(pngInput,pngOut);
        IOUtils.copy(bpmnInput,bpmnOut);
//        8、关闭流
        pngOut.close();
        bpmnOut.close();
        pngInput.close();
        bpmnInput.close();
    }

operation result

Insert picture description here


Insert picture description here