Schema is not dropped on hbmddl.auto = create.drop

筅森魡賤 提交于 2019-11-29 10:36:38

That comment is actually incorrect. Since quite a long time ago, the true behavior of "create-drop" as compared to just "create" is that the former drops the schema when the SessionFactory is closed. "create" itself does what the comment says, which is to drop the schema and recreate it on startup. For verification, setting "org.hibernate" logging to trace will show that with either "create" or "create-drop", the schema is dropped and then created at startup:

INFO - Running hbm2ddl schema export
DEBUG - import file not found: /import.sql
INFO - exporting generated schema to database
TRACE - total checked-out connections: 0
TRACE - using pooled JDBC connection, pool size: 0
DEBUG - alter table Bar drop constraint FK103F39E150191
DEBUG - Unsuccessful: alter table Bar drop constraint FK103F39E150191
DEBUG - Table "BAR" not found; SQL statement:
alter table Bar drop constraint FK103F39E150191 [42102-149]
DEBUG - drop table Bar if exists
DEBUG - drop table Foo if exists
DEBUG - create table Bar (id integer generated by default as identity, foo_id integer, primary key (id))
DEBUG - create table Foo (id integer generated by default as identity, primary key (id))
DEBUG - alter table Bar add constraint FK103F39E150191 foreign key (foo_id) references Foo
INFO - schema export complete

However, on shutdown (SessionFactory.close()), the "create" gives

INFO - closing
INFO - cleaning up connection pool: jdbc:h2:file:D:/dev/projects/testbed/test-db-for-hibernate-create-drop

whereas with "create-drop", you'll see

INFO - closing
INFO - Running hbm2ddl schema export
DEBUG - import file not found: /import.sql
INFO - exporting generated schema to database
TRACE - total checked-out connections: 0
TRACE - using pooled JDBC connection, pool size: 0
DEBUG - alter table Bar drop constraint FK103F39E150191
DEBUG - drop table Bar if exists
DEBUG - drop table Foo if exists
INFO - schema export complete
TRACE - returning connection to pool, pool size: 1
INFO - cleaning up connection pool: jdbc:h2:file:D:/dev/projects/testbed/test-db-for-hibernate-create-drop

You can try it yourself:

git clone git@github.com:zzantozz/testbed tmp
cd tmp
mvn compile exec:java -Dexec.mainClass=rds.hibernate.Main -pl hibernate-create-drop
Gao Hao

You probably forgot to call sessionFactory.close() like the mistake I made. An abrupt exit won't do the clean elegantly.

With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.

Hibernate Community Documentation, Chapter 3. Configuration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!