gpt4 book ai didi

grails-orm - 在 Grails (GORM) 中,如何覆盖约束名称

转载 作者:行者123 更新时间:2023-12-04 18:05:29 29 4
gpt4 key购买 nike

Grails (GORM) ,如何覆盖约束名称(在生成的 dbm 脚本中)。我正在将 Oracle 与 GORM 一起使用。
似乎约束名称的长度限制为 15。

如果无法覆盖,那么有没有办法将长度更改为超过 15(比如 25)!!

例如

CREATE TABLE X ( 
id NUMBER(19,0) NOT NULL,
CONSTRAINT overridden_name_here
PRIMARY KEY (id));

最佳答案

在 Grails 3 中,如果您使用的是 Hibernate 4.x,您只需要扩展类 HibernateMappingContextConfiguration 并覆盖 secondPassCompile 方法以自定义外键名称。但是,如果您想使用 Hibernate 5,解决方案略有不同。参见 graeme 对 slack grails-community 的评论:

Not our fault. Hibernate 5 is significantly different so we had to adapt. They essentially deprecated the Configuration hierarchy as well as changed how you hook into metadata. For Hibernate 5.2 this is going to have to change again.



所以,为了解决这个与 Hibernate 5 和 Grails 3 相关的问题,我做了下面的实现。首先我们需要覆盖默认的休眠实现:
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.ImplicitForeignKeyNameSource;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;

public class ReadableImplicitNamingStrategy extends ImplicitNamingStrategyJpaCompliantImpl {

public static final ReadableImplicitNamingStrategy INSTANCE = new ReadableImplicitNamingStrategy();

private String getPlural(String tableName) {

final int len = tableName.length();
final boolean isLower = Character.isLowerCase(tableName.charAt(len - 1));
final String s = tableName.toLowerCase();
final char lastChar = s.charAt(len - 1);

String result = tableName;

switch (lastChar) {
case 'y':
result = tableName.substring(0, tableName.length() -1) + (isLower? "ie": "IE"); break;
case 's':
case 'x':
case 'z':
result = tableName.substring(0, tableName.length() -1) + (isLower? "e": "E"); break;
default:
if (s.endsWith("sh")) {
result = tableName.substring(0, tableName.length() -1) + (isLower? "e": "E");
}
}
result += (isLower? "s": "S");
return result;
}

@Override
public Identifier determineForeignKeyName(ImplicitForeignKeyNameSource source) {

StringBuilder sb = new StringBuilder("FK_")
.append(source.getReferencedTableName().getText())
.append("_")
.append(getPlural(source.getTableName().getText()));

return toIdentifier(sb.toString(), source.getBuildingContext());

}
}

此外,我们必须创建一个类来自定义 Gorm 配置:
import org.grails.orm.hibernate.cfg.HibernateMappingContextConfiguration

class GormConfiguration extends HibernateMappingContextConfiguration {

@Override
protected void reset() {
super.reset();
this.implicitNamingStrategy = ReadableImplicitNamingStrategy.INSTANCE;
}

}

最后,在 application.yml 中引用我们将在 DataSource 中使用的自定义类。
dataSource:
dbCreate: update
configClass: mypackage.GormConfiguration

关于grails-orm - 在 Grails (GORM) 中,如何覆盖约束名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29464282/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com