Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In a simple inheritance tree, an abstract superclass 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.

like image 202
Gareth Avatar asked Dec 08 '25 15:12

Gareth


1 Answers

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.

like image 150
Thierry Avatar answered Dec 10 '25 05:12

Thierry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!