2

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

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
abhi
  • 1,920
  • 6
  • 24
  • 27
  • Does this answer your question? [Execute a Create Table Query through the JPA EntityManager](https://stackoverflow.com/questions/6141794/execute-a-create-table-query-through-the-jpa-entitymanager) – Seb Feb 06 '20 at 07:45

2 Answers2

2

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.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
  • I noticed that when I annotate the method with @transactional. it gets invoked even when I am not invoking the method – abhi Feb 07 '20 at 17:18
1

EntityManager.createQuery will cannot used for DML Statements. Use EntityManager.createNativeQuery.

Matthias
  • 1,378
  • 10
  • 23