java - Spring CrudRepository deleteAll() 什么都不做
问题描述
当我尝试通过 Spring 的 CrudRepository 从我的数据库中删除所有记录时测试控制器类,但似乎什么也没发生。默认情况下似乎不刷新。
我从来没有在浏览器中的真实控制器调用中尝试过这个存储库,只是使用 Junit 测试,但我认为它可以正常工作!:)
@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> {
}
hibernate.show_sql=true
启用后根据@TheCoder 注释显示sql ,结果为:
deleteAll()
上@After
:_
@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_
输出 sqldeteleAll()
上的包括删除查询。@AfterTransaction
@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中,添加repository.deleteAllInBatch()
内部@BeforeEach
方法后对我有用。仅在执行 junit 期间遇到此问题。
@BeforeEach
public void config()
{
repository.deleteAllInBatch()
}
推荐阅读
- java - 使用多个版本而无需重新安装
- javascript - 这个rxjs合并逻辑可以简化吗?
- batch-file - 在单独的命令提示符下运行复杂的命令
- python - 将 0 和 1 的 2d 矩阵转换为图形/绘图
- amazon-web-services - 主键 dynamoDB 的用户 ID 与 ID
- sql - SELECT DISTINCT + ORDER BY 附加表达式
- netbeans - 如何在 NetBeans 工具链模块中指定与 MinGW 不同的目录中的编译器
- mobile - 弹出移动/PWA 链接
- java - hibernate servlet获取jsp页面错误404
- git - BeyondCompare git difftool -d 立即关闭,无需等待用户