Skip to content

Quick Start Guide

Kais OMRI edited this page Sep 6, 2018 · 4 revisions

Quick Start Guide

First, grab RelMongo dependency into your pom or build.gradle :

   <dependency>
      <groupId>io.github.kaiso.relmongo</groupId>
      <artifactId>relmongo</artifactId>
      <version>x.y.z</version>
   </dependency>

See compatibility matrix for versions to use.

RelMongo is very simple to use.
given two concepts with "one to *" relation

  __________________                         __________________
 |    Person        |                       |    Car           |
 |__________________| 1                  *  |__________________|
 |  name (string)   |---------------------->|   ....           |
 |  cars (list )    |                       |                  |
 |                  |                       |                  |
 |__________________|                       |__________________|

on your Person mongo entity simply add the following annotations from RelMongo :

    @OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
    @JoinProperty(name="cars")
    private List<Car> cars;

and on your Spring App config class simply add @EnableRelMongo annotation:

    ... Other Annotations
    @EnableRelMongo
    public Class AppConfig
    

test your code :

        Car car = new Car();
        car.setColor(Color.BLUE);
        String manufacturer = "BMW";
        car.setManufacturer(manufacturer);
        Person person = new Person();
        person.setName("person");
        person.setEmail("[email protected]");
        person.setCars(Arrays.asList(new Car[] {car}));
        repository.save(person);
        Optional<Person> retreivedPerson = repository.findById(person.getId().toString());
        assertFalse(retreivedPerson.get().getCars().isEmpty());
        assertTrue(retreivedPerson.get().getCars().get(0).getColor().equals(Color.BLUE));
        

database layout when executing this test :

  • cars collection :
{
    _id : ObjectId(5afaff0e2557db3a140d0f85),
    manufacturer : BMW,
    color : BLUE
}
  • persons collection
  {
    _id : ObjectId(5afaff0e2557db3a140d0f86),
    name : person,
    email : person@mail.com,
    cars : [ 
        {
            _id : ObjectId(5afaff0e2557db3a140d0f85)
            _relmongo_target: cars
        }
    ]
}