1

How can I make a field required in Data Transfer Model definition of morphia mongo Db? For example

    public class ExapmleDto {
        @Id
        private String _id;
        private String userName;
    }

In this code i want to make username a mandatory field.

ZINDA ROBOT
  • 280
  • 2
  • 15

1 Answers1

1

You have multiple options:

  1. Java: When you call save on your object, check that the username is set.
  2. Index: Set a unique index on username. As long as you don't set sparse = true, there can only be a single document with a null username. With Morphia the code looks like this (annotate on the entity): @Indexes(@Index(fields = {@Field("userName")}, options = @IndexOptions(unique = true)))
  3. Document validation: MongoDB will introduce document validation with 3.2 (which is just around the corner). However, Morphia doesn't support this yet (if it ever will) so you'll need to set this yourself in the MongoDB shell.
xeraa
  • 10,456
  • 3
  • 33
  • 66