Store enum name, not value in database using EBean
Asked Answered
P

1

7

I have this enum :

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;
    }
}

And a model like this :

@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;
}

I match the enum using this in my controller :

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

The problem is that in database, it's stored as "Microsoft Word documents", but I would prefer to store it as DOC.

How can I do that?

Peder answered 18/7, 2012 at 12:30 Comment(0)
F
11

You can define it very fine granular with the Anotation EnumMapping or EnumValue. This works with the old version org.avaje.ebean.

It seems that there was a complete rewrite of the code. In the actual version there is a different approach.

Fecundate answered 19/7, 2012 at 10:51 Comment(1)
Both links are dead now, can you add some description to this?Therontheropod

© 2022 - 2024 — McMap. All rights reserved.