将枚举名称而非值存储在数据库中使用EBean

7

我有一个枚举:

public enum DocumentTypes {
    PDF("PDF Document"), JPG("Image files (JPG)"), DOC("Microsoft Word documents");

    private final String displayName;

    DocumentTypes(final String display) {
        this.displayName = display;
    }

    @Override
    public String toString() {
        return this.displayName;
    }
}

这是一个这样的模型:

@Entity
@Table(name = "documents")
public class Document extends Model {
    @Id
    public Long id;
    
    @Constraints.Required
    @Formats.NonEmpty
    @Enumerated(EnumType.STRING)
    @Column(length=20, nullable=false)
    public DocumentTypes type;

    @Constraints.Required
    @Formats.NonEmpty
    @Column(nullable=false)
    public String document;
}

我在我的控制器中使用以下方法匹配枚举:

DynamicForm form = form().bindFromRequest();
// ...
Document doc = new Document();
doc.type = DocumentTypes.valueOf(form.field("type").value());
doc.save();

问题是在数据库中,它被存储为“Microsoft Word文档”,但我更喜欢将其存储为DOC。您如何做到这一点?
1个回答

11
您可以使用注释 EnumMappingEnumValue 对其进行非常细粒度的定义。这适用于旧版本 org.avaje.ebean。
看起来代码已经完全重写了。 在当前版本中,有一种不同的 方法

这两个链接现在都失效了,你能否添加一些描述呢? - TheChetan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接