本文介绍了我可以在每个层次的Hibernate表继承策略中跨子类重用一列吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在简单的继承树中,抽象超类具有两个子类.

In a simple inheritance tree, an abstract superclass has two subclasses.

这两个子类都存储一个键-值对,但是一个子类将保存一个Encrypted String类型,另一个子类保存一个普通的旧String.

The subclasses both store a key-value pair, but but one will be holding a type Encrypted String, and the other one a plain old String.

现在,我的问题是我可以这样做吗?

Now, my question is can I do this:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract Attribute {
    @Id
    private Integer id;

    @Column(name="attribute_key")
    private String key;
}

@Entity
public EncryptedAttribute extends Attribute {
    @Column(name="attribute_value")
    private EncryptedString encryptedValue;
}

@Entity
public UnEncryptedAttribute extends Attribute {
    @Column(name="attribute_value")
    private String plainValue;        
}

加密的字符串和纯字符串都应该在数据库中都以varchars结尾,但是我可以在同一列中存储与不同子类关联的持久属性吗?这样可以避免将空值存储在特定行中未使用的列中的瑞士奶酪"副作用.

The Encrypted String and plain String should both end up as varchars in the db, but can I store persistent attributes associated with different sub-classes in the same column? This would avoid the "swiss-cheese" side-effect of storing null values in columns which aren't used in a particular row.

推荐答案

可以.(我会在您的情况下这样做)

Yes you can. (And i would do that in your case)

但是,您将遇到一些限制:这两个属性的最大长度都相同.

However, you will encounter some constraints :both properties will have the same max length.

在子类之间共享类似列的地方更令人质疑的是外键.假设您希望两个外键(每个子类一个)引用不同的表,那么如果您使用同一列,则将无法设置外键约束.

Where sharing a column like that between subclasses is more questionable is on foreign keys. Suppose you want the two foreign keys (one in each subclass) to reference different tables, you won't be able to set a foreign key constraint if you use the same column.

另一方面,如果两个外键都是强制性的,但是您选择使用两个不同的列以便具有fk约束,则将无法设置非空约束.

On the other hand, if both foreign keys are mandatory but you choose to use two different columns so that you can have fk constraints, you won't be able to set a not-null constraint.

这篇关于我可以在每个层次的Hibernate表继承策略中跨子类重用一列吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 16:48