【问题标题】:`TransientPropertyValueException` when updating Spring Boot from 2.6.7 to 2.7.2将 Spring Boot 从 2.6.7 更新到 2.7.2 时出现“TransientPropertyValueException”
【发布时间】:2022-08-11 20:27:24
【问题描述】:

我在 Spring Boot 集成测试类中有以下代码:

@Autowired
private AddressRepository addressRepository;
// other Repositories that all extend CrudRepository 

@BeforeEach
void init(){
  Address address = new Address();
  // Set up address
  address = addressRepository.save(address); //<-- address properly persisted?

  Building building = new Building();
  building.setAddress(address); 
  buildingRepository.save(building); //<-- throws error
}

在哪里

@Entity
class Building {
  @ManyToOne(fetch = FetchType.LAZY, optional = false)
  Address address;
  //...
}

和 pom.xml:

//...
 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.2</version>//<-- upping the version breaks things
    <relativePath/>
  </parent>
//...

在 Spring Boot 2.6.7 上运行流畅。然而,在升级到 2.7.2 之后,保存 building 现在会抛出 org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation。如果我理解正确,Spring 认为 address 尚未持久化,因此无法将其引用存储在 building 中。但它已经坚持在init 的第二行?

我错过了什么?

  • 您在 BeforeEach 中没有交易,这就是它失败的原因。但我不能告诉你为什么它以前有效。

标签: java spring-boot jpa


【解决方案1】:

TL;DR:不应该在测试中完成@Transactional,除非你知道你在做什么,H2 很奇怪。

为什么@Transactional 不是一个好主意?

默认情况下,每个测试都已经包含在自己的事务中(docs)。这就是它事先工作的原因。嵌套另一个 Transaction 似乎实际上使 Spring 感到困惑,因为它似乎不再像它应该做的那样自动提交每个操作。

H2很奇怪

问题是Address(请注意Address不是我的真实代码,而是对象相似关系的示例)使用UUID作为它的id,我们的testDB H2没有从@987654328正确创建@ 并使用错误的类型创建了 id 列。因此,它无法通过id 找到任何Address。这就是为什么 JPAContext 错误地说地址不存在的原因。

添加

  //...
  @Entity
  public class Address{
  @Column(columnDefinition = 'uuid') <-- add this line
  @Id
  UUID addrId;
  //...
}

帮助 M2 确定正确的列类型并解决问题。

【讨论】:

    猜你喜欢
    • 2022-12-22
    • 1970-01-01
    • 2022-10-01
    • 2022-08-14
    • 2022-12-22
    • 2022-10-18
    • 2020-11-11
    • 2020-09-14
    • 1970-01-01
    相关资源
    最近更新 更多