0

I recently asked this question : Spring Mongodb - Insert Nested document?

And found out that Spring-Data-MongoDB does not support such behavior - so now I need a working alternative.

Now - to avoid having you look at the code on another page, I am going to paste it here from the other question... Here are my two POJOs :

@Document
public class PersonWrapper {

    @Id
    private ObjectId _Id;

    @DBRef
    private Person leader;

    @DBRef
    List<Person> delegates;

    // Getters and setters removed for brevity.
}

public class Person
{
    @Id
    private ObjectId _Id;

    private String name;

    // Getters and setters removed for brevity.
}

Now, what I want to be able to do here - is send up a JSON object in my POST request as follows :

{
    "personWrapper":
    {
        "_Id":"<ID HERE (MIGHT WANT SQL TO GENERATE THIS DURING CREATE>",
        "leader":{
            "_Id":"<ID HERE (MIGHT WANT SQL TO GENERATE THIS DURING CREATE>",
            "name":"Leader McLeaderFace"
        },
        delegates:[{...},{...},{...}]
    }
}

At this point - I would like the SQL side of this to create the individual records needed - and then insert the PersonWrapper record, with all of the right foreign keys to the desired records, in the most efficient way possible.

To be honest, if one of you thinks I am wrong about the Spring-Data-MongoDB approach to this, I would still be interested in the answer - because it would save me the hassle of migrating my database setup. So I will still tag the spring-data-mongodb community here, too.

Community
  • 1
  • 1
IWishIWasABarista
  • 413
  • 2
  • 4
  • 19

1 Answers1

0

If I understand well you want to cascade the save of your objects ?

ex : you save a PersonWrapper with some Person in the delegates property and spring data will save PersonneWrapper in a collection and save also the list of Person in another Collection.

It is possible to do that with Spring DATA JPA if you annotate your POJO with the JPA annotation @OneToMany and setup cascade property of this annotation. See this post

However the cascade feature is not available for Spring DATA mongoDB. See documentation .First you have to save the list of Person and then you save PersonWrapper.

Community
  • 1
  • 1