Search code examples
spring-bootjpaspring-data-jpaentitymanager

DROP a table using Spring Boot


I want execute drop table query on my database using spring JPA (Database- Postgres)

This is my code:

public void executeDropTable(String tableName){

    String query = "DROP TABLE IF EXISTS :tableName";

    entityManager.createQuery(query)
            .setParameter("tableName", tableName)
            .executeUpdate();

}

But in IntelliJ shows error as 'DROP' unexpected on a query string

enter image description here


Solution

  • You should get something like this:

    java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: DROP near line 1, column 1 [DROP TABLE webinar_speakers]

    The DROP statement is not valid HQL.

    Use a native query instead and don't forget @Transactional:

    @Transactional
    public void executeDropTable(String tableName) {
        // ...
        entityManager.createNativeQuery(...) // ...
    }
    

    The fact that DROP is highlighted most likely comes from the Spring Data plugin for IntelliJ which "knows" that DROP is not valid in this context. If you use createNativeQuery(...) DROP won't be highlighted anymore.