I have some model with two relations:
@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
}
I use Spring Data JPA
and I want to update entity. I write simple service:
@Service
public class DataModelService {
@Autowired
private DataModelRepository dataModelRepository;
@Transactional
public DataModel createOrUpdate(DataModel dataModel) {
return dataModelRepository.save(dataModel);
}
//another methods
}
I write simple test:
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());
}
}
But, I get error, when I try to call method getQieries()
:
Unable to evaluate the expression Method threw 'org.hibernate.LazyInitializationException' exception.
Questions:
outputFields
field filled in correctly, but the queries
field is not? It happens because you are trying to initialize collection outside a transaction. To fix this add @DataJpaTest
and @RunWith(SpringRunner.class)
annotations to your test class. By default, data JPA tests are transactional.
Refer here for more details.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.