简体   繁体   中英

Create Schema (Table) using Hibernate

I have a jar file in which there are set of models annotated as @Entity . Now I want to create tables in database corresponding to models in jar file (I can use jar file as in dependency in pom file by installing jar on local repository). And it should be generic (eg MySQL, Postgresql, oracle, ms sql server, h2....). I am new in hibernate. Can any one suggest me how can I do this.

With the help of org.hibernate.tool.hbm2ddl.SchemaExport we can achieve this task.
Example :

Configuration configuration = new Configuration();
//we can set property here e.g configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");.....
configuration = configuration.configure();
SchemaExport schemaExport  = new SchemaExport(configuration);
schemaExport.create(false, true); //1st parameter indicated to show query on console and 2nd parameter is to create(update) table in database. 

From docs you can use

hibernate.hbm2ddl.auto

Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.

validate | update | create | create-drop

from this

1)validate: validate the schema, makes no changes to the database.

2)update: update the schema.

3)create: creates the schema, destroying previous data.

4)create-drop: drop the schema at the end of the session.

Hope that helps

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