Hibernate 5隐式命名策略 [英] Hibernate 5 ImplicitNamingStrategy

查看:86
本文介绍了Hibernate 5隐式命名策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用休眠5.x.使用hibernate 5.x,有ImplicitNamingStrategyPhysicalNamingStrategy的新接口.

I want to use hibernate 5.x. With hibernate 5.x there are new interfaces for ImplicitNamingStrategy and PhysicalNamingStrategy.

对于实体User的属性name,我想在数据库中具有列名user_name.我不想用@Column(name="...")注释每个属性.我试图编写一个自定义ImplicitNamingStrategy,但是无法获取拥有实体的名称.

For a property name of an entity User I want to have a column name user_name in my database. I do not want to annotate every property with @Column(name="..."). I tried to write a custom ImplicitNamingStrategy but there is no way to get the name of the owning entity.

public class MyNamingStrategy extends ImplicitNamingStrategyComponentPathImpl
{
    @Override
    public Identifier determineBasicColumnName ( ImplicitBasicColumnNameSource source )
    {
        // How to get the name of the owning entity?
        String owningEntityName = "howdoigetthis"; 
        Identifier basicColumnName = super.determineBasicColumnName(source);
        Identifier identifier = Identifier.toIdentifier(owningEntityName +"_" + basicColumnName.toString());
        return identifier;
    }
}

是否有一种仅通过使用NamingStrategy在表(或实体)名称上加上前缀的方法?

Is there a way to prefix every column with the table (or entity) name by just using a NamingStrategy?

推荐答案

如果您不介意一些肮脏的思考,这是一个解决方案:

Here's a solution if you don't mind a bit of dirty reflection:

@Override
public Identifier determineBasicColumnName(final ImplicitBasicColumnNameSource source)
{
    // Get 'this$0' field and make it accessible
    Field ejb3ColumnField = null;
    final Field[] sourceFields = source.getClass().getDeclaredFields();
    for (final Field sourceField : sourceFields) {
        if (sourceField.getName().equals("this$0")) {
            ejb3ColumnField = sourceField;
        }
    }
    ejb3ColumnField.setAccessible(true);

    // Get actual field object
    String owningEntityName;
    Ejb3Column ejb3Column;
    try {
        ejb3Column = (Ejb3Column) ejb3ColumnField.get(source);
    } catch (
        IllegalArgumentException
        | IllegalAccessException e) {
        throw new RuntimeException(e);  // (Or deal with this appropriately, e.g. log it.)
    }

    // The property holder path holds the owning entity's fully qualified name
    final String owningEntityFullyQualifiedName = ejb3Column.getPropertyHolder().getPath();

    // The entity name is after the last dot in the fully qualified name
    final String[] owningEntityTokens = owningEntityFullyQualifiedName.split("\\.");
    owningEntityName = owningEntityTokens[owningEntityTokens.length - 1];

    final Identifier basicColumnName = super.determineBasicColumnName(source);
    return Identifier.toIdentifier(owningEntityName + "_" + basicColumnName.toString());
}

这篇关于Hibernate 5隐式命名策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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