8

Is there any Spring Annotation to Set Default value for a Field (Mongo) ?

Gaurav Agrawal
  • 909
  • 1
  • 10
  • 20
  • Which version of Spring are you using? I believe you've got the wrong answer from the ***answer*** below, it is better for you to check this answer: http://stackoverflow.com/a/28134682/1867076 – Prometheus Dec 27 '16 at 12:43

2 Answers2

20

No need for spring annotations, this should do the trick:

     import org.springframework.data.mongodb.core.mapping.Document;
     import org.springframework.data.mongodb.core.mapping.Field;


    @Document
    public class Doc {

    @Field
    private String field = "CustomDefaultValue"; 

    }
felix
  • 9,007
  • 7
  • 41
  • 62
  • Is there any spring annotation ? – Gaurav Agrawal Dec 27 '16 at 11:34
  • @GauravAgrawal No, there's nothing like this. Available annotations are available here : http://docs.spring.io/spring-data/data-document/docs/current/reference/html/#mapping-usage-annotations – felix Dec 27 '16 at 11:37
  • 1
    not really a good idea because if the same model used for data coming from the front-end it's hard to tell whether it's a default value or it's provided from the front-end. – Next Developer Mar 23 '20 at 22:05
  • this would probably work `public String getImageType() { return imageType == null ? 'PNG' : imageType; }` and I'm don't think `@Field` annotation is needed – Rivenfall Aug 04 '20 at 15:16
1

You have to tell your Builder to use default value for some field using @Builder.Default(annotation).

Like this,

    @Builder
    @Document
    public class Document {

    @Builder.Default
    private String field = "any_value"; 

    }
Gaurav Raghav
  • 157
  • 1
  • 6