• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Paul Clapham
  • paul wheaton
Sheriffs:
  • Tim Cooke
  • Devaka Cooray
  • Rob Spoor
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:

Spring and MongoDB manual references

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi everyone,

I need advice on doing manual references in mongodb with spring without using dbrefs.

If for example, I have two document collections:

User {
...
addresses: [addressId1, addressId2...]
}

Address {
..
}

So, user has 1 or more addresses. In user document, I want to use array of address ids.

Now, there is a question of inserting, updating and retrieving user document.

For insertion, I would need one POJO which has addresses as array of ids (array of ObjectIds, Strings..).

For retrieving, sometimes I need full document with addresses eagerly populated. For this case I would need different POJO which has addresses as array of address objects.

Is there any good approach to this? Any pieces of advice?
 
Rancher
Posts: 516
15
Notepad Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The User and Address data is a one-to-many relationship. A user can have, in general, 1 to 3 ( a small number) addresses. In MongoDB, this is modeled by embedding the address data into the user data.

It is unusual, to create two collections one for each of the user and the address - especially when the addresses are going to be a very small number, and the kind of data being stored. The document structure would be something like this in a "user" collection:



Note the address is an array type field, with multiple address elements.

The two Java POJOs are the User and the Address. The User class will have a property called as address of type List<Address>. Using Spring-Data APIs for MongoDB, the CRUD operations can be performed on the "user" collection. For example, using MongoTemplate class:



References:
  • Data Model Design
  • MongoTemplate


  • NOTE: One can also consider using MongoDB Java Driver APIs for the same application.

     
    Did you ever grow anything in the garden of your mind? - Fred Rogers. Tiny ad:
    a bit of art, as a gift, that will fit in a stocking
    https://gardener-gift.com
    reply
      Bookmark Topic Watch Topic
    • New Topic