在删除和重新创建数据库之后强制Hibernate创建表

我正在使用java 2 ee开发一个Web应用程序。 我也使用hibernate和mysql。 为了恢复备份文件,在我的应用程序的某些时候我需要删除当前数据库并重新创建它,我按如下方式执行:

Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/?user=user&password=pass"); Statement statement = (Statement) conn.createStatement(); statement.executeUpdate("DROP DATABASE tcs;"); statement.executeUpdate("CREATE DATABASE tcs charset=utf8 collate=utf8_persian_ci;"); 

删除并重新创建后我需要使用默认用户初始化数据库(spring security user)

  User admin = new User(); UserAuthority ROLE_USER = new UserAuthority("ROLE_USER"); ROLE_USER.save(); admin.addUserAuthority(ROLE_USER); admin.setEnabled(true); admin.save(); 

但在最后一行应用程序抛出此exception

 Hibernate: insert into roles (authority) values (?) [DEBUG][16:19:17,734] [http-bio-8080-exec-10] NewPooledConnection:367 com.mchange.v2.c3p0.impl.NewPooledConnection@bcbe33a handling a throwable. com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'tcs.roles' doesn't exist 

我知道hibernate在启动时会创建表,但在这种情况下,它无法在删除/重新创建后重新创建表,那么我如何强制hibernate再次创建表? 或者假设有类似Hibernate.createTable(Class)东西?

您需要将以下属性添加到配置中:

每次创建和销毁SessionFactory时删除并重新创建:

 create-drop 

其他可能的选择:

  • validate:validation模式,不对数据库进行任何更改。
  • 更新:更新架构。
  • create:创建架构,销毁以前的数据。

对于未来的googlers:它毕竟是如此简单,我只需要建立会话工厂所以我添加了这一行,它就像魅力:

new Configuration()。configure()。buildSessionFactory();

请注意, buildSessionFactory()在hibernate 4中已弃用,但我想你可以使用这里的代码来做同样的事情。