如何在 Java 应用程序中使用 Hibernate 和 MySQL 清除或删除数据库
Howto clear or drop database with Hibernate & MySQL within a Java app
是否有 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();
}
解决方案
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();
}
是否有 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();
}
解决方案
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();
}