简体   繁体   中英

Hibernate Check if DB exists

I'm creating a db using an initial.sql

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3310/mydb?createDatabaseIfNotExist=true&amp;autoReconnect=true&amp;useSSL=false</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">qet</property>
<property name="format_sql">true</property>
<property name="hibernate.hbm2ddl.import_files_sql_extractor">org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.hbm2ddl.import_files">/database/initial.sql</property>

it works perfectly but the problem now is that I have the db but when I restart the app it will insert more data.

How do I check if the schema already exists dont do anything. I just want to create the db if it doesn't have any tables / doesn't exist...

Try switching the property to update

<property name="hibernate.hbm2ddl.auto">update</property>

Create recreates it every time and update creates it only if it doesn't exist. The standard values can be seen here:

https://docs.jboss.org/hibernate/orm/5.0/manual/en-US/html/ch03.html

  • validate : validates the schema
  • update : update if there are changes, create if it doesn't exist
  • create : recreate it from scratch
  • create-drop : creates it and then drops it when the session factory is closed

Also from the same reference we can see that import files are executed only if the hbm2ddl is create or create-drop

File order matters, the statements of a give file are executed before the statements of the following files. These statements are only executed if the schema is created ie if hibernate.hbm2ddl.auto is set to create or create-drop.

If you want that initial_sql to be executed you can leave it as create and you can make that SQL to have the proper commands that don't change the state if already executed. Like DROP TABLE IF EXISTS , CREATE TABLE IF NOT EXISTS etc. For inserts it is a bit more complicated but you can still do it by insert into table join the same table where value is not found

That's not the perfect solution though because if you have tables created from annotated classes they will be recreated. I think you should think about another design or use hibernate.hbm2ddl.auto=create when deploying for the first time and then changing it to update manually

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM