我撰寫了這個存盤庫,包括一個自定義查詢:
@Repository
interface PersonRepository : JpaRepository<Person, UUID> {
@Query("UPDATE Person SET firstname = :firstname, lastname = :lastname WHERE id IN :ids")
@Modifying
fun updateNames(firstname: String, lastname: String, ids: List<UUID>) : Int
}
并為其實施了以下測驗:
@DataJpaTest
@AutoConfigureTestDatabase(replace = NONE)
internal class PersonRepositoryIntegrationTest {
@Autowired
lateinit var personRepository: PersonRepository
@Test
@Commit
fun updateNames() {
// GIVEN
// insert some records
personRepository.save(Person(UUID.randomUUID(), "Homer", "Simpson"))
personRepository.save(Person(UUID.randomUUID(), "Bart", "Simpson"))
personRepository.save(Person(UUID.randomUUID(), "Marge", "Simpson"))
// read back the ids and assert lastname before updating
val readBeforeUpdate = personRepository.findAll()
assertTrue(readBeforeUpdate.isNotEmpty())
assertTrue(readBeforeUpdate.all { it.lastname == "Simpson" })
val ids = readBeforeUpdate.map { it.id }
// WHEN
val count = personRepository.updateNames("John", "Doe", ids)
personRepository.flush()
// THEN
assertEquals(3, count)
val readAfterUpdate = personRepository.findAll()
println(readAfterUpdate)
assertEquals(3, readAfterUpdate.size)
assertTrue(readAfterUpdate.all { it.firstname == "John" && it.lastname == "Doe" })
}
}
在最后一行失敗,驗證所做的更改,例如名字和姓氏。我添加@Commit
了防止自動回滾彈簧會做的事情,這樣我以后可以檢查資料。我可以在資料庫中看到更改的名稱,所以看起來我的查詢有效。我的懷疑是,val readAfterUpdate = personRepository.findAll()
要么
- 在不同的事務中執行,
personRepository.updateNames
并且無法“看到”另一個事務的更改 - 或者
personRepository.findAll()
是從 Hibernate 的快取中回傳的什么的
我在這里想念什么?如何使測驗作業?或者還有什么方法可以檢查資料庫中的資料是否確實發生了變化?
展示該行為的示例專案可在https://github.com/timbuethe/SpringBootDataTest獲得
uj5u.com熱心網友回復:
我認為使用@Modifiying
使持久性背景關系過時,所以也許添加(clearAutomatically = true)
可以解決問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/470365.html