Spring 批处理找不到在处理过程中保留的实体

Spring batch can't find entity persisted while processing

在我们的一个 spring 批处理作业中,我们在处理过程中创建了额外的实体 (CompanyProfile) 并将它们保存到数据库(在单独的事务中)。这些实体被其他实体 (Vacancy) 引用,这些实体将由编写器持久化,但不幸的是,编写器失败并出现此错误:

   Caused by: javax.persistence.EntityNotFoundException: Unable to find com.company.CompanyProfile with id 1409881

型号如下:

@Entity
public class Vacancy {
    @ManyToOne(fetch = FetchType.EAGER, optional = true)
    @JoinColumn(name = "company", nullable = true)
    private CompanyProfile company;
...
}

@Entity
public class CompanyProfile {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
...
}

在处理器中我们有这个:

CompanyProfile company = companyProfileService.handleCompany(compName);
vacancy.setCompany(company);

其中方法 companyProfileService.handleCompany() 被注释为 @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW )

我确定 CompanyProfile 得到了持久化 - 我可以在数据库中看到它,但是当 VacancyItemWriter 保存时,它失败并出现上述异常. (另请注意,在上面的异常中提到了持久化实体的 ID)

您是否看到作者在这种情况下会失败的任何原因?

根据您提供的信息,我猜测 SB 打开的事务无法看到 companyProfileService.handleCompany() 方法保存的数据,因为服务组件使用与 SB 不同的事务;你必须检查数据库 ISOLATION_LEVEL 属性