![](/img/trans.png)
[英]How can I create a table in my DB, after dropping all of my tables in database?
[英]Force Hibernate To Create Tables After Dropping and Recreating database
我正在使用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();
但在最后一行应用程序抛出此异常
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时删除并重新创建:
<property name="hbm2ddl.auto">create-drop</property>
其他可能的选择:
对于未来的googlers:它毕竟是如此简单,我只需要建立会话工厂,所以我添加了这一行,它就像魅力:
new Configuration()。configure()。buildSessionFactory();
请注意, buildSessionFactory()
在hibernate 4中已弃用,但我想你可以使用这里的代码来做同样的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.