删除Hibernate中的外键约束。

huangapple go评论81阅读模式
英文:

Remove foreign key in Hibernate DDL

问题

Hibernate会生成与JPA关联相关的外键,但是否有办法使这些外键成为可选的或禁用它们,而不需要在我的JPA类中添加任何注释?

用于生成DDL的代码如下:

Configuration cfg = new Configuration();
cfg.addResource(mappingFile);
cfg.setProperties(props);
SchemaExport scEx= new SchemaExport(cfg);
scEx.setDelimiter(";");
scEx.setOutputFile("mySCRIPT.sql");
scEx.setFormat(true);
scEx.execute(false, false, false, true);

请注意,这段代码是用来生成DDL的,如果你想要控制生成的DDL中的外键约束,通常需要在JPA实体类中使用注解来指定外键的行为。如果你想要使外键成为可选的或禁用它们,你需要根据JPA规范在实体类中添加相应的注解。

英文:

As we know Hibernate ddl is generating foreign key related to the JPA relation but Is there any way to make this foreign keys optionnal or disable it without adding any annotation in my JPA classes

this is the code used to generate the ddl :

Configuration cfg = new Configuration();
cfg.addResource(mappingFile);  
cfg.setProperties(props);
SchemaExport scEx= new SchemaExport(cfg);
scEx.setDelimiter(";");
scEx.setOutputFile("mySCRIPT.sql");
scEx.setFormat(true);
scEx.execute(false, false, false, true);

答案1

得分: 0

根据我所了解(我已经在 Hibernate 内部进行了全面查找),并没有简单的方法来做这件事。如果你真的想要做,可以通过更改处理外键的 org.hibernate.tool.schema.internal.SchemaCreatorImpl 中的代码来实现:

final Iterator fkItr = table.getForeignKeyIterator();

但是要这样做,你需要为一些 'service' 接口定义不同的实现。
此外,你还需要从这个类中复制很多代码,因为目前没有针对外键的钩子。
(虽然有一个用于自定义命名策略的钩子,但那不是你想要的)

不管怎样,如果你只是不想创建这些约束,可以将它们从生成的脚本中删除,然后手动执行该脚本,而不是让 Hibernate 自动执行。

英文:

There is no simple way to do it as far as I'm concerned (I've looked all over the hibernate internals).
You can do it if you really want, you need to change code in org.hibernate.tool.schema.internal.SchemaCreatorImpl that deals with the foreign keys:

final Iterator fkItr = table.getForeignKeyIterator();

But in order to do so you need to define some different implementations of some 'service' interfaces..
Also you will have to copy a lot of code from this class since there is no hook for the foreign keys.
(There is hook for a custom naming strategy, but this isn't what you want)

Anyway, if you just don't want to create those constraints, you can simple remove them from the generated script and manually execute it rather than letting hibernate run execute it

huangapple
  • 本文由 发表于 2020年8月24日 23:07:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63563706.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定