Spring Data MongoRepository Saving Objects with Differing Numbers of Fields

user2779450 :

I am storing game states in a MongoDB database and am using Spring Data to manage my database interactions. I am new to Spring Data and am unsure how to deal with the following scenario.

I have a document of type "Game" with a bunch of properties such as id, timestamp, etc... One of these properties is a list of actions taken by users. These actions are of the form:

{ type: 2 }, {type: 3, value: 4}, {type: 5, id: 1234}, {type 6}, {type: 5, value: 6, id: 56}

In other words, an action can have three properties: type, value, and id. However, not every action requires all three values to be stored. I want to avoid having a bunch of null values in my database, and would like my database to just not include and id or a value if they are not specified.

Using Spring Data's MongoRepository model, I am not sure how to achieve this. I can create a CRUD Game class and have one of its properties be a list of Action (where Action itself is a CRUD class with properties type, value, and id), but won't that end up storing null values in the database if I do not specify the value or id?

In short, how can I use Spring Data's MongoRepository but still maintain the flexibility of being able to store lists of objects with varying parameters or object types in general.

prasad_ :

I will explain how varying fields are handled with an example. The following Game.java POJO class represents the object mapping to the game collection document.

public class Game {

    String name;
    List<Actions> actions;

    public Game(String name, List<Actions> actions) {
        this.name = name;
        this.actions = actions;
    }

    public String getName() {
        return name;
    }

    public List<Actions> getActions() {
        return actions;
    }

    // other get/set methods, override, etc..


    public static class Actions {

        Integer id;
        String type;

        public Actions() {
        }

        public Actions(Integer id) {
            this.id = id;
        }

        public Actions(Integer id, String type) {
            this.id = id;
            this.type = type;
        }

        public Integer getId() {
            return id;
        }

        public String getType() {
            return type;
        }

        // other methods
    }
}

For the Actions class you need to provide constructors with the possible combinations. Use the appropriate constructor with id, type, etc. For example, create a Game object and save to the database:

Game.Actions actions= new Game.Actions(new Integer(1000));
Game g1 = new Game("G-1", Arrays.asList(actions));
repo.save(g1);

This is stored in the database collection game as follows (queried from mongo shell):

{
        "_id" : ObjectId("5eeafe2043f875621d1e447b"),
        "name" : "G-1",
        "actions" : [
                {
                        "_id" : 1000
                }
        ],
        "_class" : "com.example.demo.Game"
}

Note the actions array. As we had stored only the id field in the Game.Actions object, only that field is stored. Even though you specify all the fields in the class, only those provided with values are persisted.

These are two more documents with Game.Actions created with type only and id + type using the appropriate constructors:

{
        "_id" : ObjectId("5eeb02fe5b86147de7dd7484"),
        "name" : "G-9",
        "actions" : [
                {
                        "type" : "type-x"
                }
        ],
        "_class" : "com.example.demo.Game"
}
{
        "_id" : ObjectId("5eeb034d70a4b6360d5398cc"),
        "name" : "G-11",
        "actions" : [
                {
                        "_id" : 2,
                        "type" : "type-y"
                }
        ],
        "_class" : "com.example.demo.Game"
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Spring Data MongoRepository between for int values

Spring data mongorepository, find by inner object field

Not saving data of some fields

Saving nested objects with spring data - using an id as a reference

Spring Data Mongodb & Spring Boot - autowiring MongoRepository from Mongolab

Keep reference data in application memory in spring application (spring MongoRepository)

Entries with differing number of fields

Spring Data MongoRepository save(T) not working... sometimes

Custom @Query annotated method for update query with spring data MongoRepository

Custom @Query annotated method for update query with spring data MongoRepository

Spring Data- MongoRepository : Can we have binary type as the _id?

What's the difference between Spring Data's MongoTemplate and MongoRepository?

Saving an array of objects to Core Data

copying objects with data fields

How to ignore saving few fields in ElasticSearch for spring-data-elasticsearch 4.x, Elastic 7.6

Spring MongoRepository is Null

Autowire MongoRepository in Spring MVC

ModelForm saving over model data with empty fields

Saving data to Order custom fields with API in Infusionsoft

How to get slices of differing numbers of rows while subsetting by group in an R data.table

How can I create a data.frame from a nested list with differing numbers of variable

Saving and retrieving custom objects in Core Data

Saving class data containing pyqt objects

Saving data from form with multiple objects

Java Spring : MongoRepository count() and findAll()

Spring Boot MongoRepository ignoring validation

Spring MongoRepository, where to catch the exception?

Resolve variable name for MongoRepository in Spring

MongoRepository JSON Date Query (Spring)

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive