开发者

Is there a simple workflow to generate a database schema from classes with hibernate mappings?

Id 开发者_运维百科like to define my objects then use hibernate to generate my ddl from this. But it seems like the only real workflow with hibernate is to generate a datbase schema and then reverse engineer it. Am I wanting to do something that makes no sense?


Yes there is a property hibernate.hbm2ddl.auto. The documentation says:

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.

e.g. validate | update | create | create-drop

There are multiple ways to define this property, depending on how you configure your SessionFactory. The hibernate way is to simply add:

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


But it seems like the only real workflow with hibernate is to generate a database schema and then reverse engineer it.

No, absolutely not. Historically, Hibernate supports several approaches:

  • Top down: You start with the object model, then create mapping metatdata either with XML files or annotations and then generate the schema using Hibernate's hbm2ddl tool.

  • Bottom up: You start with an existing database and generate mappings and Java classes (or just annotated Java classes) from the database schema using hbm2hbmxml and hbm2java .

  • Middle out: You start be writing Hibernate XML mappings and generate DDL and Java classes using hbm2ddl and hbm2java respectively.

  • Meet in the middle: You have an existing Java model and an existing database. Hibernate tooling can't help much here, you'll very likely have to write mappings by hand and do some refactoring of the database, or of the Java code, or use some kind of bridge. This is the worst situation.

So, as we saw, Hibernate supports several workflows and provides tooling for them. And in your case, you're looking for the tool called hbm2ddl (also known as SchemaExport, which is the name of the class implementing it). There are several ways to use it:

  • You can run SchemaExport programmatically.
  • You can enable automatic export of the schema at SessionFactory creation time by setting the property hibernate.hbm2ddl.auto to an appropriate value
  • You can use the <hbm2ddl> Ant task

References

  • Hibernate Core Reference Guide
    • 3.4. Optional configuration properties
  • Hibernate Tools Reference Guide
    • 4.4.1. Database schema exporter (<hbm2ddl>)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜