Many of the many in mongodb using spring configuration (annotation recommended)

I am modeling a circuit. Since I'm new to Mongo DB, I have no idea how to model nosql db. Structuring the relational type db and using mongo on top of it does not allow me to use much for many comparisons.

Using Spring -data provides one for many support, using @DBRef on top of List<?> . But many for many - this is what I want.

Any help would be greatly appreciated. Please prefer to use the code for explanation. Or a demo structure for illustration. Thanks in advance.

+5
source share
2 answers

MongoDB implements several ways to implement many-to-many.

I think the simplest one is:

Many-to-many Relational scenario:

Many-to-many relational script

After de-normalization:

After the de-normalization scenario

And your Spring data code should look something like this:

 public class Category { @Id private ObjectId id; private String category_name; @DbRef private List<Product> products_ids; // ... getters and setters ... } public class Product { @Id private ObjectId id; private String product_name; @DbRef private List<Category> categories_ids; // ... getters and setters ... } 
+8
source

@marianomdq: And your Spring data code should look something like this: ...

When I tried this, there is no problem that it never would be to save objects in the database. My problem loads them again. This, apparently, leads to the fact that the loading of the category (in this example) falls into an infinite loop. Category → Product → Category → Produ ..... Until a StackOverflowException is thrown.

 java.lang.StackOverflowError: null at java.lang.reflect.Constructor.newInstance(Constructor.java:416) ~[na:1.8.0_77] at java.lang.Class.newInstance(Class.java:442) ~[na:1.8.0_77] at com.mongodb.DBCollectionObjectFactory.getInstance(DBCollectionObjectFactory.java:51) ~[mongodb-driver-3.2.2.jar:na] at com.mongodb.DBObjectCodec.readDocument(DBObjectCodec.java:340) ~[mongodb-driver-3.2.2.jar:na] at com.mongodb.DBObjectCodec.decode(DBObjectCodec.java:136) ~[mongodb-driver-3.2.2.jar:na] at com.mongodb.DBObjectCodec.decode(DBObjectCodec.java:61) ~[mongodb-driver-3.2.2.jar:na] ........ 

The full stacktrace is very large.

Solution : lazy loading database links!

Just set the lazy DBRef annotation flag to true, this will make the download links lazy. This means that circular links will not load immediately.

@DBRef(lazy = true)

The research that really came to this decision was cumbersome. So I wanted to share this information.

+5
source

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


All Articles