繁体   English   中英

我们如何更改在休眠状态下生成PK和FK名称的方法?

[英]How can we change method for generating PK and FK names in hibernate?

例如,我可以提供一些算法来生成FK030HF9840303的内置接口吗?

您需要实现自己的NamingStrategy(org.hibernate.cfg.NamingStrategy)。 子类化当前使用的方法也许是最简单的方法(默认情况下,休眠使用的是DefaultNamingStrategy)。

然后使用您的命名策略配置sessionFactory:

SessionFactory sf = new Configuration()
    .setNamingStrategy(new YourNamingStrategy())
    .addFile(...)
    .buildSessionFactory();

或者如果您正在使用会话工厂上的spring依赖注入,请使用它:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
...
  <property name="namingStrategy">
    <ref bean="namingStrategy" />
  </property>
...

您不能使用注释或命名策略覆盖任何内容。 例如,无法使用命名策略指定联接表的FK,而使用注释则很麻烦。

如果愿意以相同的方式配置所有内容,则可以在将模式导出到数据库之前修改批注配置。

AnnotationConfiguration configuration = ...;
Iterator<Table> tables = configuration.getTableMappings();
...
Iterator<ForeignKey> keys = table.getForeignKeyIterator();
while ( keys.hasNext() ) {
ForeignKey key = keys.next();
key.setName( ... );
}
...

SchemaExport schemaExport = new SchemaExport( configuration );
schemaExport.setHaltOnError( true );
schemaExport.execute( false, true, false, true );
List exceptions = schemaExport.getExceptions();
...

同样,如果您要使用特定的非程序命名策略,则只需更改hbm.xml文件的外键映射即可。 它是所有相关集合的属性,等等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM