3.11.1. Extending an Entity

In the application project, derive an entity class from com.haulmont.cuba.security.entity.User and add the required attribute with the corresponding access methods:

@Entity(name = "sales$ExtUser")
@Extends(User.class)
public class ExtUser extends User {

    @Column(name = "ADDRESS", length = 100)
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

The new name of the entity should be specified in the @Entity annotation. Since the parent entity does not declare the inheritance strategy, it is assumed to be SINGLE_TABLE by default. It means that the child entity will be stored in the same table as the parent one, and the @Table annotation is not required. Other parent entity annotations ( @NamePattern, @Listeners, etc.) are automatically applied to the child entity, but can be overridden in its class.

An important element of the new entity class is the @Extends annotation, which takes the parent class as a parameter. It enables creating a registry of child entities and forces the platform mechanisms to use them everywhere instead of the parent ones. The registry is implemented by the ExtendedEntities class, which is a Spring bean named cuba_ExtendedEntities, and is also accessible via the Metadata interface.

Add a localized name of the new attribute to the com.sample.sales.entity package:

messages.properties

ExtUser.address=Address

messages_ru.properties

ExtUser.address=Адрес

Register the new entity in the persistence.xml file of the project:

<class>com.sample.sales.entity.ExtUser</class>

Add the update script for the corresponding table to the database create and update scripts:

-- add column for "address" attribute
alter table SEC_USER add column ADDRESS varchar(100)
^
-- add discriminator column required for entity inheritance
alter table SEC_USER add column DTYPE varchar(100)
^
-- set discriminator value for existing records
update SEC_USER set DTYPE = 'sales$ExtUser' where DTYPE is null
^

In order to use new entity attributes in screens, create views for the new entity with the same names as the views of the base entity. A new view should extend the base view and define new attributes, for example:

<view class="com.sample.sales.entity.ExtUser"
      name="user.browse"
      extends="user.browse">

    <property name="address"/>
</view>

The extended view will include all attributes from its parent view. An extended view is not required if the base one extends _local and you add only local attributes, so in the described case this step can be omitted.