gpt4 book ai didi

java - 返回更新的实体后出现 LazyInitializationException

转载 作者:行者123 更新时间:2023-12-01 16:56:40 26 4
gpt4 key购买 nike

我有一些具有两种关系的模型:

@Entity
@Table(name = "data_model")
public class DataModel {

@Id
@GeneratedValue
@Column(name = "model_id")
private Integer id;

@Column(name = "name")
private String name;

@OneToMany(mappedBy = "dataModel", cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE})
private List<OutputField> outputFields;

@OneToMany(mappedBy = "dataModel", cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE})
private List<Query> queries;

//some another fields
}

我使用 Spring Data JPA 并且我想更新实体。我写了简单的服务:

@Service
public class DataModelService {

@Autowired
private DataModelRepository dataModelRepository;

@Transactional
public DataModel createOrUpdate(DataModel dataModel) {
return dataModelRepository.save(dataModel);
}

//another methods
}

我编写了简单的测试:

public class DataModelServiceTest {
@Autowired
private DataModelService dataModelService;

@Test
void shouldUpdateDataModel() {
DataModel dataModelBeforeUpdate = dataModelService.getById(1);
dataModelBeforeUpdate.getQueries().get(0).setSqlQuery("SELECT 1");
DataModel updatedModel = dataModelService.createOrUpdate(dataModelBeforeUpdate);
assertThat(updatedModel.getQueries(), notNullValue());
}
}

但是,当我尝试调用方法 getQieries() 时,出现错误:

Unable to evaluate the expression Method threw 'org.hibernate.LazyInitializationException' exception.

在调试中我看到: enter image description here

问题:

  1. 为什么会出现此错误以及如何修复它?如何让 hibernate 在更新后返回所有链接?
  2. 为什么 outputFields 字段填写正确,但 queries 字段填写不正确?

最佳答案

发生这种情况是因为您尝试在事务之外初始化集合。要解决此问题,请在测试类中添加 @DataJpaTest@RunWith(SpringRunner.class) 注释。默认情况下,数据 JPA 测试是事务性的。

引用here了解更多详情。

关于java - 返回更新的实体后出现 LazyInitializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61577561/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com