使用EBean存储枚举名称,而不是数据库中的值

问题描述 投票:6回答:1

我有这个枚举:

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。

我怎样才能做到这一点 ?

谢谢你的帮助!

enums playframework-2.0 ebean
1个回答
10
投票

您可以使用Annotation EnumMappingEnumValue定义非常精细的粒度。这适用于旧版本org.avaje.ebean。

似乎完全重写了代码。在实际版本中有一个不同的approach

© www.soinside.com 2019 - 2024. All rights reserved.