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



我有这个枚举:

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。

我该怎么做?

您可以使用Antation EnumMapping或EnumValue对其进行非常精细的定义。这适用于旧版本org.avaje.ebean.

似乎对代码进行了彻底的重写。在实际版本中,有一种不同的方法。

最新更新