15. 流管理持久性

大多数应用程序都以某种方式访问数据。 许多 API 会修改多个用户共享的数据,因此需要事务性数据访问属性。 它们通常将关系数据集转换为域对象以支持应用程序处理。 Web Flow 提供“流管理持久性”,其中流可以为您创建、提交和关闭对象持久性上下文。 Web Flow 集成了 Hibernate 和 JPA 对象持久性技术。spring-doc.cadn.net.cn

除了流 Management 持久性之外,还有完全封装的模式PersistenceContext管理。 在这种情况下,Web 层不涉及持久性。 相反,它完全适用于传递给服务层并由服务层返回的分离对象。 本章重点介绍流托管持久性,探讨如何以及何时使用此功能。spring-doc.cadn.net.cn

15.1. 流范围PersistenceContext

此模式会创建一个PersistenceContextflowScope在流程启动时,在流程执行过程中使用该上下文进行数据访问,并在结束时提交对持久实体所做的更改。 此模式通过在流程执行结束时将更改提交到数据库来提供中间编辑的隔离。 此模式通常与 Optimistic 锁定策略结合使用,以保护多个用户并行修改的数据的完整性。 为了支持在较长时间内保存和重新启动流的进度,必须使用流状态的持久存储。 如果不需要保存和重新启动功能,则基于 HTTP 会话的标准流状态存储就足够了。 在这种情况下,会话在提交之前过期或结束可能会导致更改丢失。spring-doc.cadn.net.cn

要使用 flow-scopedPersistenceContextpattern 中,首先将 flow 标记为persistence-context如下:spring-doc.cadn.net.cn

<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.springframework.org/schema/webflow"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/webflow
                          https://www.springframework.org/schema/webflow/spring-webflow.xsd">

    <persistence-context />

</flow>

然后配置正确的FlowExecutionListener将此模式应用于您的流。 如果您使用 Hibernate,请注册HibernateFlowExecutionListener. 如果您使用 JPA,请注册JpaFlowExecutionListener. 以下示例使用 JPA:spring-doc.cadn.net.cn

<webflow:flow-executor id="flowExecutor" flow-registry="flowRegistry">
    <webflow:flow-execution-listeners>
        <webflow:listener ref="jpaFlowExecutionListener" />
    </webflow:flow-execution-listeners>
</webflow:flow-executor>

<bean id="jpaFlowExecutionListener"
      class="org.springframework.webflow.persistence.JpaFlowExecutionListener">
    <constructor-arg ref="entityManagerFactory" />
    <constructor-arg ref="transactionManager" />
</bean>

要在最后触发提交,请注释end-state元素,如下所示:spring-doc.cadn.net.cn

<end-state id="bookingConfirmed" commit="true" />

就是这样。 当您的流程启动时,侦听器会处理分配一个新的EntityManagerflowScope. 您可以引用此EntityManager随时在您的流程中,使用特殊的persistenceContext变量。 此外,当您使用 Spring 管理的数据访问对象时发生的任何数据访问都会自动使用此对象EntityManager. 此类数据访问作应始终以非事务性或只读事务方式运行,以保持中间编辑的隔离。spring-doc.cadn.net.cn

15.2. 流 Management 持久性和子流

流管理PersistenceContext会自动扩展(传播)到子流,假设每个子流也具有<perstistence-context/>变量。 当子流重用PersistenceContext由其父级启动,当达到 End 状态时,它会忽略提交标志,从而将最终决定(提交或不提交)推迟到其父级。spring-doc.cadn.net.cn