Enumerations

An enumeration is a set of constants that can be used as values of an entity attribute.

In Jmix, an enumeration is a Java enum implementing the EnumClass interface and having an id field of Integer or String type. This field is stored in the database instead of ordinal() or name() of the enum, which has the following advantages:

  • You can rename and reorder enum constants, and as long as you keep the identifiers, your data model will be compatible with the database content.

  • Even if the database contains a value that does not correspond to any enum constant (it happens if an old and a new versions of an application work with the same database), the entity still can be loaded with the enum attribute containing null. With the standard JPA approach, loading of such an instance is impossible at all.

Use Studio enumeration designer to create Jmix enumerations.

Below is an example of Jmix enumeration class:

CustomerGrade.java
public enum CustomerGrade implements EnumClass<String> { (1)

    BRONZE("B"), (2)
    GOLD("G"),
    PLATINUM("P");

    private String id;

    CustomerGrade(String value) {
        this.id = value;
    }

    public String getId() { (3)
        return id;
    }

    @Nullable
    public static CustomerGrade fromId(String id) { (3)
        for (CustomerGrade at : CustomerGrade.values()) {
            if (at.getId().equals(id)) {
                return at;
            }
        }
        return null;
    }
}
1 The EnumClass interface is parameterized by the Id type (String in this case).
2 Each enum constant is defined with a corresponding Id value passed to the constructor.
3 getId() and fromId() methods convert an enum constant to its Id and back.

The enum should be used in an entity as follows:

Customer.java
@Column(name = "GRADE")
private String grade; (1)

public CustomerGrade getGrade() { (2)
    return grade == null ? null : CustomerGrade.fromId(grade);
}

public void setGrade(CustomerGrade grade) { (2)
    this.grade = grade == null ? null : grade.getId();
}
1 The persistent field has the type of the enum’s identifier (Integer or String)
2 Getter and setter convert from Id type to the enum type and back.
When creating an attribute in Studio entity designer, select ENUM in the Attribute type field and find your enum in the Type field.