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

时间:2013-06-08 11:53:07

标签: 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;");
删除并重新创建后,我需要使用默认用户(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)的东西?

2 个答案:

答案 0 :(得分:3)

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

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

<property name="hbm2ddl.auto">create-drop</property>

其他可能的选择:

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

答案 1 :(得分:1)

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

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

请注意,buildSessionFactory()在hibernate 4中已弃用,但我猜您可以使用代码here执行此操作。

相关问题