Store enumeration name, not value in database using EBean

I have this listing:

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 such a model:

 @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 map 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 it is stored as “Microsoft Word documents” in the database, but I would prefer to save it as a DOC.

How can i do this?

Thanks for your help!

+6
source share
1 answer

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

There seems to have been a complete redesign of the code. In the real version, there is a different approach .

+10
source

Source: https://habr.com/ru/post/920796/


All Articles