Hibernate JPA @MetaValue Eample

@MetaValue

The @MetaValue annotation is used by the @AnyMetaDef annotation to specify the association between a given discriminator value and an entity type.

MetaValue

Maps a given discriminator value to the corresponding entity type. See Any for more information.

Any

Defines a ToOne-style association pointing to one of several entity types depending on a local discriminator, as opposed to discriminated inheritance where the discriminator is kept as part of the entity hierarchy. For example, if you consider an Order entity containing Payment information where Payment might be of type CashPayment or CreditCardPayment the @Any approach would be to keep that discriminator and matching value on the Order itself. Thought of another way, the "foreign-key" really is made up of the value and discriminator (there is no physical foreign key here as databases do not support this):
    @Entity
    class Order {
        ...
        @Any( metaColumn = @Column( name="payment_type" ) )
        @AnyMetDef(
                idType = "long"
                metaValues = {
                        @MetaValue( value="C", targetEntity=CashPayment.class ),
                        @MetaValue( value="CC", targetEntity=CreditCardPayment.class ),
                }
        )
        pubic Payment getPayment() { ... }
    }
 }


@Any mapping

The @Any mapping is useful to emulate a unidirectional @ManyToOne association when there can be multiple target entities.

Because the @Any mapping defines a polymorphic association to classes from multiple tables, this association type requires the FK column which provides the associated parent identifier and a metadata information for the associated entity type.

The @Any annotation describes the column holding the metadata information. To link the value of the metadata information and an actual entity type, the @AnyDef and @AnyDefs annotations are used. The metaType attribute allows the application to specify a custom type that maps database column values to persistent classes that have identifier properties of the type specified by idType. You must specify the mapping from values of the metaType to class names.

@Any mapping usage

@Entity
@Table( name = "property_holder" )
public class PropertyHolder {

    @Id
    private Long id;

    @Any(
        metaDef = "PropertyMetaDef",
        metaColumn = @Column( name = "property_type" )
    )
    @JoinColumn( name = "property_id" )
    private Property property;

    //Getters and setters are omitted for brevity

}

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation