【问题标题】:Howto clear or drop database with Hibernate & MySQL within a Java app如何在 Java 应用程序中使用 Hibernate 和 MySQL 清除或删除数据库
【发布时间】:2016-08-30 01:43:44
【问题描述】:

是否存在 mysql 查询(使用 MariaDB 10.x.x)或 Hibernate HQL,其中单个数据库中的所有表都被删除?现在我正在尝试使用下面的代码,但它对数据库没有任何作用。由于我使用的是 Hibernate 5.x.x,所以createSQLQuery 已贬值;因此我使用createNativeQuery 而不是

tx = s.beginTransaction();
            Session s = getSessionFactory().openSession();
        Transaction tx = null;

        try {
            tx = s.beginTransaction();
            s.createNativeQuery("SET FOREIGN_KEY_CHECKS = 0");
            s.createNativeQuery("DROP DATABASE restaurantapp");
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            s.close();
        }

【问题讨论】:

  • 您已连接到数据库,然后删除数据库。听起来不是很好的方法。
  • 所以你是说我应该断开与数据库的连接然后删除它?如果是这样,您能告诉我如何实现它的步骤吗?

标签: mysql database hibernate mariadb


【解决方案1】:

解决方案

SQL 命令很好,但我不知道我需要在每个原生查询之后添加.executeUpdate();

解决方案代码:

Session s = getSessionFactory().openSession();
        Transaction tx = null;

        try {
            tx = s.beginTransaction();
            s.createNativeQuery("SET FOREIGN_KEY_CHECKS = 0").executeUpdate();
            s.createNativeQuery("DROP DATABASE restaurantapp").executeUpdate();
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            s.close();
        }

【讨论】:

    猜你喜欢
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    • 2019-12-27
    相关资源
    最近更新 更多