SpringBoot:集成Activiti6工作流完成模拟订单任务(jpa+Mysql)(采用特定人员方式)

1.声明

当前内容主要为本人学习和测试在SpringBoot中使用jpa以及mysql方式操作当前的activiti6这个工作流

2.基本的pom依赖

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>1.2.6.RELEASE</version><!-- 父类中的版本控制所有的依赖包的版本信息 -->
	<relativePath />
</parent>
<properties>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
	<!-- https://mvnrepository.com/artifact/org.activiti/activiti-spring-boot-starter-basic -->
	<dependency>
		<groupId>org.activiti</groupId>
		<artifactId>activiti-spring-boot-starter-basic</artifactId>
		<version>6.0.0</version>
	</dependency>
	<!-- 使用jpa功能 -->
	<dependency>
		<groupId>org.activiti</groupId>
		<artifactId>activiti-spring-boot-starter-jpa</artifactId>
		<version>6.0.0</version>
	</dependency>
	<!-- 添加web支持 -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
		<!-- <version>1.2.6.RELEASE</version> -->
	</dependency>
	<!-- 添加h2数据库支持 -->
	<!-- <dependency>
		<groupId>com.h2database</groupId>
		<artifactId>h2</artifactId>
		<version>1.4.183</version>
	</dependency> -->
	<!-- 添加mysql数据库支持 -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.34</version>
	</dependency>
	<dependency>
		<groupId>org.apache.tomcat</groupId>
		<artifactId>tomcat-jdbc</artifactId>
		<version>8.0.15</version>
	</dependency>
	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>3.8.1</version>
		<scope>test</scope>
	</dependency>
</dependencies>

3.基本订单的流程配置

<?xml version="1.0" encoding="UTF-8"?>
<definitions
        xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
        xmlns:activiti="http://activiti.org/bpmn"
        targetNamespace="Examples" >
    <process id="orderTaskProcess" name="订单流程">
        <startEvent id="orderStart" />
        <sequenceFlow id="order-flow1" sourceRef="orderStart" targetRef="selectOrder" />
        <userTask id="selectOrder" name="选择订单" activiti:assignee="${username}" />
        <sequenceFlow id="order-flow2" sourceRef="selectOrder" targetRef="conformOrder" />
        <userTask id="conformOrder" name="确认订单" activiti:assignee="${username}" />
        <sequenceFlow id="order-flow3" sourceRef="conformOrder" targetRef="submitOrder" />
        <userTask id="submitOrder" name="提交订单" activiti:assignee="${username}" />
        <sequenceFlow id="order-flow4" sourceRef="submitOrder" targetRef="orderEnd" />
        <endEvent id="orderEnd" />
    </process>

</definitions>

注意这里的activiti:assignee="${username}"对应传递给activiti的变量中的username属性

4.配置文件

db.properties

mysql.url=jdbc:mysql://localhost:3306/hy_activiti6
mysql.username=root
mysql.password=root
mysql.driverClassName=com.mysql.jdbc.Driver

application.properties

spring.jpa.hibernate.ddl-auto=update

5.demo

1.基本的配置类:AppConfig

import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.hy.springboot.activiti6.pojo.MySqlDBProperties;

@Configuration
@PropertySource(value = { "classpath:db.properties" })
@EnableConfigurationProperties(value = MySqlDBProperties.class)
@EnableTransactionManagement
public class AppConfig {

	@Bean(name = "dataSource")
	public DataSource setDataSource(MySqlDBProperties properties) {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setUrl(properties.getUrl());
		dataSource.setUsername(properties.getUsername());
		dataSource.setPassword(properties.getPassword());
		dataSource.setDriverClassName(properties.getDriverClassName());
		return dataSource;
	}
}

2.基本实体类

MySqlDBProperties

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "mysql")
public class MySqlDBProperties {
	private String url;
	private String driverClassName;
	private String username;
	private String password;
	// 省略getter和setter方法
}

Person实体类

import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * 
 * @author hy
 * @createTime 2021-03-20 14:18:57
 * @description 对应数据库的实体类,主要用于处理哪个人执行的工作流
 *
 */
@Entity
public class Person {

	@Id
	@GeneratedValue
	private Long id;

	private String username;

	private Date birthDate;

	public Person() {
	}

	public Person(String username, Date birthDate) {
		this.username = username;
		this.birthDate = birthDate;
	}

	// 省略getter和setter方法
}

3.dao和service层

PersonRepository

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.hy.springboot.activiti6.pojo.Person;

/**
 * 
 * @author hy
 * @createTime 2021-03-20 14:19:20
 * @description 默认采用jpa方式实现数据操作方式
 *
 */
@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {

	Person findByUsername(String username);
}

OrderService

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hy.springboot.activiti6.dao.PersonRepository;
import com.hy.springboot.activiti6.pojo.Person;

@Service
public class OrderService {

	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	private TaskService taskService;

	@Transactional //默认开启
	public void startProcess() {
		// 开启订单任务	 
		//指定xml配置文件为:admin
		  runtimeService.startProcessInstanceByKey("orderTaskProcess");
	}
	
	@Transactional
	// 为某个人开始activiti工作流程(指定用户名的方式实现)
	public void startProcess(String username) {
		// 开启订单任务
		
		  Map<String, Object> variables = new HashMap<String, Object>();
		  variables.put("username", username);
		 
		//指定xml配置文件为:
		  runtimeService.startProcessInstanceByKey("orderTaskProcess",variables);
	}

	// 获取需要指定的任务列表
	@Transactional
	public List<Task> getTasks(String username) {
		return taskService.createTaskQuery().taskAssignee(username).list();
	}

	// 完成某个任务
	@Transactional
	public void completeTask(String taskId) {
		taskService.complete(taskId);
	}

	@Autowired
	private PersonRepository personRepository;

	public void createDemoUsers() {
		if (personRepository.findAll().size() == 0) {
			personRepository.save(new Person("zhangsan", new Date()));
			personRepository.save(new Person("admin", new Date()));
		}
	}

}

4.controller层

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hy.springboot.activiti6.dao.PersonRepository;
import com.hy.springboot.activiti6.pojo.Person;
import com.hy.springboot.activiti6.service.OrderService;

/**
 * 
 * @author hy
 * @createTime 2021-03-20 14:19:41
 * @description 一个标准的订单控制器,向当前的activiti中执行流程控制操作
 *
 */
@RestController
public class OrderController {

	@Autowired
	private OrderService orderService;

	// 开启工作流任务
	/*
	 * @RequestMapping(value = "/process", method = RequestMethod.GET) public void
	 * startProcessInstance() { orderService.startProcess(); }
	 */
	
	// 开启工作流任务
	@RequestMapping(value = "/process", method = RequestMethod.GET)
	public void startProcessInstance(@RequestParam String username) {
		orderService.startProcess(username);
	}
	
	// 完成工作流中的某项任务
	@RequestMapping(value = "/complete", method = RequestMethod.GET)
	public void completeTask(@RequestParam String taskId) {
		orderService.completeTask(taskId);
	}
	

	// 获取当前的执行工作流的列表(即具有哪些未完成的工作流)
	@RequestMapping(value = "/tasks", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public List<TaskRepresentation> getTasks(@RequestParam String username) {
		List<Task> tasks = orderService.getTasks(username); // 获取某个人的执行任务流程的状态
		List<TaskRepresentation> dtos = new ArrayList<TaskRepresentation>();
		for (Task task : tasks) {
			dtos.add(new TaskRepresentation(task.getId(), task.getName()));
		}
		return dtos;
	}

	static class TaskRepresentation {

		private String id;
		private String name;

		public TaskRepresentation(String id, String name) {
			this.id = id;
			this.name = name;
		}
		
		// 省略getter和setter方法
	}

}

5.入口类

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.hy.springboot.activiti6.service.OrderService;

@EntityScan(basePackages = { "com.hy.springboot.activiti6.pojo" })
@EnableJpaRepositories(basePackages = { "com.hy.springboot.activiti6.dao" })
@SpringBootApplication
public class SpringBootActiviti6App {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootActiviti6App.class, args);
	}

	@Bean
	public CommandLineRunner init(final OrderService orderService, final RepositoryService repositoryService,
			final RuntimeService runtimeService, final TaskService taskService) {

		return new CommandLineRunner() {

			@Override
			public void run(String... strings) throws Exception {
				System.out.println(
						"Number of process definitions : " + repositoryService.createProcessDefinitionQuery().count());
				System.out.println("Number of tasks : " + taskService.createTaskQuery().count());
				// 开始创建基本的用户,如果数据库中存在则不需要
				 orderService.createDemoUsers(); 
			}
		};

	}

}

6.测试和结果

能够正常启动并且在mysql中创建许多的表
在这里插入图片描述
完成一次流程后就会产生特定的表数据信息
在这里插入图片描述
测试结果完成

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Spring Boot 集成 Activiti 工作流的示例代码: 1. 在 pom.xml 中添加依赖: ```xml <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-spring-boot-starter-basic</artifactId> <version>${activiti.version}</version> </dependency> ``` 2. 创建一个 Activiti 配置类: ```java @Configuration public class ActivitiConfig { @Bean public ProcessEngineConfiguration processEngineConfiguration(DataSource dataSource, PlatformTransactionManager transactionManager) { SpringProcessEngineConfiguration configuration = new SpringProcessEngineConfiguration(); configuration.setDataSource(dataSource); configuration.setTransactionManager(transactionManager); configuration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE); configuration.setAsyncExecutorActivate(false); return configuration; } @Bean public ProcessEngineFactoryBean processEngineFactoryBean(ProcessEngineConfiguration processEngineConfiguration) { ProcessEngineFactoryBean factoryBean = new ProcessEngineFactoryBean(); factoryBean.setProcessEngineConfiguration(processEngineConfiguration); return factoryBean; } @Bean public RepositoryService repositoryService(ProcessEngine processEngine) { return processEngine.getRepositoryService(); } @Bean public RuntimeService runtimeService(ProcessEngine processEngine) { return processEngine.getRuntimeService(); } @Bean public TaskService taskService(ProcessEngine processEngine) { return processEngine.getTaskService(); } @Bean public HistoryService historyService(ProcessEngine processEngine) { return processEngine.getHistoryService(); } @Bean public ManagementService managementService(ProcessEngine processEngine) { return processEngine.getManagementService(); } @Bean public IdentityService identityService(ProcessEngine processEngine) { return processEngine.getIdentityService(); } @Bean public FormService formService(ProcessEngine processEngine) { return processEngine.getFormService(); } } ``` 3. 创建一个简单的工作流程: ```xml <?xml version="1.0" encoding="UTF-8"?> <definitions id="definitions" targetNamespace="http://www.activiti.org/test" xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd"> <process id="testProcess" name="Test Process"> <startEvent id="start" name="Start"></startEvent> <userTask id="task1" name="Task 1" assignee="${user}"></userTask> <exclusiveGateway id="gateway1"></exclusiveGateway> <userTask id="task2" name="Task 2" assignee="${user}" /> <endEvent id="end" name="End"></endEvent> <sequenceFlow id="flow1" sourceRef="start" targetRef="task1"></sequenceFlow> <sequenceFlow id="flow2" sourceRef="task1" targetRef="gateway1"></sequenceFlow> <sequenceFlow id="flow3" sourceRef="gateway1" targetRef="task2"> <conditionExpression xsi:type="tFormalExpression">${approved == true}</conditionExpression> </sequenceFlow> <sequenceFlow id="flow4" sourceRef="gateway1" targetRef="end"> <conditionExpression xsi:type="tFormalExpression">${approved == false}</conditionExpression> </sequenceFlow> </process> </definitions> ``` 4. 创建一个处理器来启动和完成工作流程: ```java @Service public class WorkflowService { private final TaskService taskService; private final RuntimeService runtimeService; @Autowired public WorkflowService(TaskService taskService, RuntimeService runtimeService) { this.taskService = taskService; this.runtimeService = runtimeService; } public void startWorkflow(String processDefinitionKey, Map<String, Object> variables) { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, variables); } public void completeTask(String taskId, Map<String, Object> variables) { taskService.complete(taskId, variables); } } ``` 5. 在控制器中使用处理器来启动和完成工作流程: ```java @RestController @RequestMapping("/workflow") public class WorkflowController { private final WorkflowService workflowService; @Autowired public WorkflowController(WorkflowService workflowService) { this.workflowService = workflowService; } @PostMapping("/start") public void startWorkflow(@RequestParam String processDefinitionKey, @RequestParam String user) { Map<String, Object> variables = new HashMap<>(); variables.put("user", user); workflowService.startWorkflow(processDefinitionKey, variables); } @PostMapping("/complete") public void completeTask(@RequestParam String taskId, @RequestParam boolean approved) { Map<String, Object> variables = new HashMap<>(); variables.put("approved", approved); workflowService.completeTask(taskId, variables); } } ``` 上述代码中,我们创建了一个 Activiti 配置类来配置 Activiti 引擎,包括数据库配置、事务管理器等。我们还创建了一个简单的工作流程,其中包括一个开始事件、两个用户任务、一个排他网关和一个结束事件。最后,我们创建了一个处理器来启动和完成工作流程,并在控制器中使用处理器来处理具体的请求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值