【问题标题】:DROP a table using Spring Boot使用 Spring Boot 删除表
【发布时间】:2020-05-21 22:05:09
【问题描述】:

我想使用 spring JPA 对我的数据库执行drop 表查询(数据库-Postgres

这是我的代码:

public void executeDropTable(String tableName){

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

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

}

但在 IntelliJ 中,在查询字符串上显示错误为 'DROP' unexpected

【问题讨论】:

标签: spring-boot jpa spring-data-jpa entitymanager


【解决方案1】:

你应该得到这样的东西:

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException:意外令牌: 在第 1 行第 1 列附近放置 [DROP TABLE webinar_speakers]

DROP 语句不是有效的 HQL。

改用原生查询,不要忘记@Transactional

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

DROP 被突出显示的事实很可能来自 IntelliJ 的 Spring Data 插件,它“知道”DROP 在这种情况下无效。如果您使用createNativeQuery(...) DROP 将不再突出显示。

【讨论】:

  • 我注意到当我用@transactional 注释方法时。即使我没有调用该方法,它也会被调用
【解决方案2】:

EntityManager.createQuery 不能用于 DML 语句。使用 EntityManager.createNativeQuery。

【讨论】:

    猜你喜欢
    • 2020-11-10
    • 2021-06-17
    • 2018-09-22
    • 2020-03-29
    • 2019-10-29
    • 2019-06-28
    • 2019-03-17
    • 1970-01-01
    • 2015-10-25
    相关资源
    最近更新 更多