gpt4 book ai didi

java - JPA不保存带有@Transactional注释的选择结果

转载 作者:行者123 更新时间:2023-12-01 19:35:29 26 4
gpt4 key购买 nike

我无法在 Spring Boot 应用程序中使用 JPA 将选择结果保存到数据库中。我使用的代码如下:

@Override
@Transactional
public void fetchAndSave() {
List<TestData> all = testDataRepository.findAllRecords();
testDataRepository.saveAll(all);
// let suppose I will save another data here that's why I need @Transactional for roll-back in case of exception
}
@Repository
public interface TestDataRepository extends JpaRepository<TestData, Long> {
@Query(value = "select raw_values.identificator AS id, raw_values.name as value from test.raw_values", nativeQuery = true)
List<TestData> findAllRecords();
}

当我使用属性 spring.jpa.show-sql=true 调用 fetchAndSave 时,我在日志中仅看到选择:

Hibernate: select raw_values.identificator AS id, raw_values.name as value from test.raw_values

如果我不使用@Transactional,我可以在日志中看到更多对数据库的请求,并保存值:

Hibernate: select raw_values.identificator AS id, raw_values.name as value from test.raw_values
Hibernate: select testdata0_.id as id1_0_0_, testdata0_.value as value2_0_0_ from test.test_data testdata0_ where testdata0_.id=?
Hibernate: select testdata0_.id as id1_0_0_, testdata0_.value as value2_0_0_ from test.test_data testdata0_ where testdata0_.id=?
Hibernate: select testdata0_.id as id1_0_0_, testdata0_.value as value2_0_0_ from test.test_data testdata0_ where testdata0_.id=?
Hibernate: insert into test.test_data (value, id) values (?, ?)
Hibernate: insert into test.test_data (value, id) values (?, ?)
Hibernate: insert into test.test_data (value, id) values (?, ?)

我在数据库中有一个非常简单的表,DDL 看起来像:

create table test_data
(
id serial not null
constraint test_data_pk
primary key,
value varchar(256)
);
-- There are 3 records in table raw_values
create table table_name
(
identificator integer not null
constraint table_name_pk
primary key,
name varchar(256)
);

你能帮我找出这种行为的原因吗?我希望使用 @Transactional 时将记录保存到数据库中。

最佳答案

“为什么不保存”的简短答案是:因为它们已经保存了。

更长的答案是 Hibernate 看到这些 ID 已经存在于数据库中,并且不会保存它们。

如果您想将另外三个实体插入数据库,只需使用 id=null 为这些对象创建重复项并保存它们:

List<TestData> all = testDataRepository.findAllRecords();
List<TestData> copies = all.stream()
.map(testData -> new TestData(...)) //copy all the fields EXCEPT ID
.collect(toList());
testDataRepository.saveAll(copies);

关于java - JPA不保存带有@Transactional注释的选择结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57837624/

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