使用JPA执行VACUUM FULL

时间:2017-10-27 19:59:34

标签: java postgresql jpa vacuum

我正在使用PostgreSQL数据库,我想使用JPA EntityManager启动VACUUM FULL

版本1

public void doVacuum(){
  entityManager.createNativeQuery("VACUUM FULL").executeUpdate()
}

抛出TransactionRequiredException

版本2

@Transactional
public void doVacuum(){
  entityManager.createNativeQuery("VACUUM FULL").executeUpdate()
}

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

版本3

public void doVacuum(){
  entityManager.createNativeQuery("VACUUM FULL").getResultList()
}

执行真空,但之后我得到PersistenceException"没有结果"

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

1 个答案:

答案 0 :(得分:2)

正如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()
}