gpt4 book ai didi

java - Spring CrudRepository deleteAll() 什么都不做

转载 作者:行者123 更新时间:2023-11-30 12:07:28 27 4
gpt4 key购买 nike

当我尝试通过 Spring 的 CrudRepository 从我的数据库中删除所有记录时测试 Controller 类,但似乎什么也没发生。默认情况下似乎没有刷新。

我从来没有在浏览器中使用 Junit 测试在真正的 Controller 调用中尝试过这个存储库,但我认为它会工作得很好! :)

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("test")
@Transactional
public class CostumerControllerIntegrationTest {

@Autowired
private MockMvc mockMvc;

@Autowired
private CostumerService costumerService;

private Costumer costumer;

@Before
public void before() {
this.costumer = this.exampleBuilder();
costumerService.saveAll(this.costumer);
}

@After
public void after() {
costumerService.deleteAll();
}

@Test
public void Should_ReturnStandardError_When_NotFoundById() throws Exception {
//implementation
}


private Costumer exampleBuilder() {

Costumer costumer = new Costumer("Test", "Test", "Test", CostumerType.LEGAL_PERSON);
State state = new State("Example State");
City city = new City("Example Sity", state);
Address address = new Address("Example Address",
"Example Address", "Example Address",
"Example Address", city, costumer);

costumer.getAddresses().add(address);

return costumer;
}

@Service
@Transactional
public class CostumerService {

@Autowired
private CostumerRepository repository;

public void deleteAll() {
repository.deleteAll();
}

//another methods

}

扩展 CrudRepository 的存储库

@Repository
public interface CostumerRepository extends CrudRepository<Costumer, Integer> {

}

根据@TheCoder注释开启显示sql hibernate.show_sql=true后,结果为:

@After 上的 deleteAll():

@After
public void after() {
costumerService.deleteAll();
}

输出sql:

2019-02-27 06:07:06 - HHH000397: Using ASTQueryTranslatorFactory
Hibernate:
select
costumer0_.id as id1_3_,
costumer0_.cpf_cnpj as cpf_cnpj2_3_,
costumer0_.email as email3_3_,
costumer0_.name as name4_3_,
costumer0_.type as type5_3_
from
costumers costumer0_

@AfterTransaction 上的deteleAll() 输出sql 包括删除查询。

@AfterTransaction
public void afterTransatcion(){
// List<Costumer> costumers = costumerService.findAll();
costumerService.deleteAll();
}


Hibernate:
select
costumer0_.id as id1_3_,
costumer0_.cpf_cnpj as cpf_cnpj2_3_,
costumer0_.email as email3_3_,
costumer0_.name as name4_3_,
costumer0_.type as type5_3_
from
costumers costumer0_
Hibernate:
delete
from
phones
where
costumer_id=?
Hibernate:
delete
from
costumers
where
id=?

最佳答案

在我的 junit 中,在 @BeforeEach 方法中添加 repository.deleteAllInBatch() 之后对我有用。仅在执行 junit 时遇到此问题。

@BeforeEach
public void config()
{
repository.deleteAllInBatch()
}

关于java - Spring CrudRepository deleteAll() 什么都不做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54891504/

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