使用 JPA 执行 VACUUM FULL

Mar*_*cel 5 java postgresql jpa vacuum

我正在使用 PostgreSQL 数据库,并且我想开始VACUUM FULL使用 JPA EntityManager。

版本1

public void doVacuum(){
  entityManager.createNativeQuery("VACUUM FULL").executeUpdate()
}
Run Code Online (Sandbox Code Playgroud)

抛出 TransactionRequiredException

版本2

@Transactional
public void doVacuum(){
  entityManager.createNativeQuery("VACUUM FULL").executeUpdate()
}
Run Code Online (Sandbox Code Playgroud)

抛出 PersistenceException“VACUUM 无法在事务块内运行”

版本3

public void doVacuum(){
  entityManager.createNativeQuery("VACUUM FULL").getResultList()
}
Run Code Online (Sandbox Code Playgroud)

执行真空,但之后我得到 PersistenceException“无结果”

启动这个sql命令的正确方法是什么?

Mar*_*cel 4

正如 Alay Hay 提到的,使用底层连接是可行的:

public void doVacuum(){
  org.hibernate.Session session = entityManager.unwrap(org.hibernate.Session);
  org.hibernate.internal.SessionImpl sessionImpl = (SessionImpl) session;  // required because Session doesn't provide connection()
  java.sql.Connection connection = sessionImpl.connection();
  connection.prepareStatement("VACUUM FULL").execute();
}
Run Code Online (Sandbox Code Playgroud)