Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Hibernate To Create Tables After Dropping and Recreating database

I am developing a web application with java 2 ee. I also use hibernate and mysql. in order to restore the backup file, in some point in my application i need to drop the current database and recreate it, i do it as follow :

    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;");

after dropping and recreating i need to initialize database with default user (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();

but at the last line application throws this 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

i know hibernate creates tables at startup but in this case it fails to recreate the tables after a drop/recreate , so how can i force hibernate to create tables again? or hypothetically is there something like Hibernate.createTable(Class) ?

like image 472
MoienGK Avatar asked Oct 04 '22 21:10

MoienGK


2 Answers

You need to add the following property to your configuration:

Drop and Recreate everytime SessionFactory is created and destroyed:

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

Other possible options:

  • validate: validate the schema, makes no changes to the database.
  • update: update the schema.
  • create: creates the schema, destroying previous data.
like image 96
Chris Avatar answered Oct 13 '22 12:10

Chris


for future googlers : it was so simple after all , i just needed to build session factory so i added this line and it worked like charm :

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

note that buildSessionFactory() is deprecated in hibernate 4 but i guess you can use the code here to do the same.

like image 23
MoienGK Avatar answered Oct 13 '22 12:10

MoienGK