gpt4 book ai didi

postgresql - 如何清理 Spring Boot 应用程序中的数据库表?

转载 作者:行者123 更新时间:2023-11-29 11:54:45 25 4
gpt4 key购买 nike

我目前的尝试(根据 this answer )如下所示:

@Service
class VacuumDatabaseService(
private val entityManager: EntityManager
) {
fun vacuumAllTables() {
val session = entityManager.unwrap(org.hibernate.Session::class.java)
val sessionImpl = session as org.hibernate.internal.SessionImpl
val connection = sessionImpl.connection()
connection.prepareStatement("VACUUM FULL").execute()
}
}

但是它抛出:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: No transactional EntityManager available

@Transactional 注释函数会导致:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.reflect.UndeclaredThrowableException

Caused by: org.postgresql.util.PSQLException: ERROR: VACUUM cannot run inside a transaction block

以下是可行的,但感觉错误得很危险:

    @Transactional
fun vacuumAllTables() {
val session = entityManager.unwrap(org.hibernate.Session::class.java)
val sessionImpl = session as org.hibernate.internal.SessionImpl
val connection = sessionImpl.connection()
connection.prepareStatement("END TRANSACTION; VACUUM FULL;").execute()
}

正确的做法是什么?

最佳答案

您只需注入(inject) DataSource,从中获取连接,执行作业,然后关闭连接。

@Service
class VacuumDatabaseService(
private val dataSource: DataSource
) {

fun vacuumAllTables() {
dataSource.connection.use {
it.prepareStatement("VACUUM FULL").execute()
}
}
}

注意 use 的用法,它会在 block 执行后关闭连接。

关于postgresql - 如何清理 Spring Boot 应用程序中的数据库表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55556923/

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