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

Moi*_*nGK 5 java mysql spring hibernate java-ee

我正在使用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;");
Run Code Online (Sandbox Code Playgroud)

删除并重新创建后我需要使用默认用户初始化数据库(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();
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

Moi*_*nGK 1

对于未来的谷歌用户:毕竟它是如此简单,我只需要构建会话工厂,所以我添加了这一行,它的工作方式就像魅力一样:

new Configuration().configure().buildSessionFactory();

请注意,它 在 hibernate 4 中已弃用,但我想您可以使用此处的buildSessionFactory()代码来执行相同的操作。