Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store enum name, not value in database using EBean

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?

like image 871
Cyril N. Avatar asked Jul 18 '12 12:07

Cyril N.


1 Answers

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.

like image 93
niels Avatar answered Sep 25 '22 03:09

niels