用hibernate更新数据库模式 [英] Update database schema with hibernate

查看:102
本文介绍了用hibernate更新数据库模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < property name =hibernate.hbm2ddl.auto>更新< / property> 

我可以创建我的数据库模式,它会自动添加属性,约束,关键等...
但是更新数据库模式呢?
如果我从我的实体中删除一些属性,hibernate不会删除它,或者如果我更改了一些约束,hibernate不会触及已经创建的约束...



因此,有一种方法可以让hibernate真正更新数据库模式?



谢谢。

解决方案

我们为自己创建了一个工具,它创建必要的数据库列和表的删除,并将这些删除添加到为数据库更新生成的SQL中。但是我们必须在SchemaUpdate代中添加一些额外功能才能使其工作:




  • 我们必须添加对非空属性的检查。这包括在数据上发布UPDATE语句以尽可能地消除空值,导致下一点的默认值。

  • 我们必须添加对列默认值的检查。默认值是由列的可空性及其数据类型推断的。基元始终被初始化为零或为false,非空枚举为其第一枚举值,但对于其他对象,必须手动修改脚本。

  • 我们甚至增加了对调整varchar列大小的支持,因为存在数据库列长度和 @Column(length)不同的情况。



但是为了将它们放在一起,不能以这种方式创建一个完整的工具,因为如果在代码中重新命名列,该怎么办?如果类型以不能自动转换的方式改变(bool至今?)会怎么样?如果您无法访问重构历史记录,则无法始终传播更改。


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

i can create my database schema, it automatically add properties, constraint, key etc... But what about UPDATE the database schema? If i remove some property from my entities, hibernate doesn't remove it, or if i change some constraint, hibernate doesn't touch constraint already created...

So, there is a way to make hibernate really update the database schema?

Thanks.

解决方案

We created a tool for our own that creates the necessary drops of database columns and tables and add these drops to the SQL generated for database updates. But we had to add some extras to the SchemaUpdate generation to make it work:

  • We had to add checks for not-null properties. This includes issuing an UPDATE statement on the data to eleminate nulls where possible, leading to the next point of default values.
  • We had to add checks for default values of columns. The defaults are inferred by the nullability of a column and its datatype. Primitives are always initialized to zero or false, not-null enums to its first enum value, but for other objects the script has to be modified manually.
  • We even added support for resizing varchar columns, because there were cases where the database column length and the @Column(length) differed.

But to put it all together, a complete tool cannot be created this way, because what if a column is renamed in code? What if the type changes in a way not automatically convertible (bool to date?). If you don't have access to a refactoring history, you cannot always propagate changes.

这篇关于用hibernate更新数据库模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆