Force hibernation to create tables after resetting and re-creating the database

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

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 deleting and re-creating, I need to initialize the database with the 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 on the last line the 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 that hibernate creates tables at startup, but in this case it cannot recreate tables after drop / rereate, so how can I get hibernate to create tables again? or hypothetically is there something like Hibernate.createTable(Class) ?

+4
source share
2 answers

for future googlers: it was so simple in the end, I just needed to create a factory session, so I added this line and it worked like a charm:

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

note that buildSessionFactory() deprecated in hibernate 4, but I think you can use the code here to do the same.

+1
source

You need to add the following property to the configuration:

Drop and re-create every time a SessionFactory is created and destroyed:

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

Other options are:

  • validate: check the schema, do not make changes to the database.
  • update: update the schema.
  • create: creates a schema, destroying previous data.
+3
source

Source: https://habr.com/ru/post/1485169/


All Articles