开发者

Can I reuse a column across subclasses in a Hibernate table-per-hierarchy inheritance strategy?

开发者 https://www.devze.com 2022-12-26 19:07 出处:网络
In a simple inheritance tree, an abstract su开发者_如何学Cperclass has two subclasses. The subclasses both store a key-value pair, butbut one will be holding a type Encrypted String, and the other on

In a simple inheritance tree, an abstract su开发者_如何学Cperclass has two subclasses.

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;        
}

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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号