Thursday, 28 November 2019

Spring boot: MongoDB: Model relationships via reference ids

We can model relationship by referencing one entity id from other entity.

For example,
@Document("addresses")
public class Address {

 @Id
 private String id;

 private String city;
 private String country;

 .....
 .....
}

@Document("employees")
public class Employee {
 @Id
 private String id;

 private String firstName;

 private String lastName;

 private String addressId;

 .....
 .....
}

As you see above snippet, I created a field 'addressId' in Employee entity, it is used to refer the id of Address entity.

Find the below working application.

Address.java
package com.sample.app.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document("addresses")
public class Address {

 @Id
 private String id;

 private String city;
 private String country;

 public Address(String city, String country) {
  super();
  this.city = city;
  this.country = country;
 }

 public String getCity() {
  return city;
 }

 public void setCity(String city) {
  this.city = city;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Address [id=").append(id).append(", city=").append(city).append(", country=").append(country)
    .append("]");
  return builder.toString();
 }

}

Employee.java
package com.sample.app.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document("employees")
public class Employee {
 @Id
 private String id;

 private String firstName;

 private String lastName;

 private String addressId;

 public Employee(String firstName, String lastName, String addressId) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.addressId = addressId;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getAddressId() {
  return addressId;
 }

 public void setAddressId(String addressId) {
  this.addressId = addressId;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
    .append(lastName).append(", addressId=").append(addressId).append("]");
  return builder.toString();
 }

}

AddressRepository.java
package com.sample.app.repository;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import com.sample.app.entity.Address;

@Repository
public interface AddressRepository extends MongoRepository<Address, String> {

}

EmployeeRepository.java
package com.sample.app.repository;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import com.sample.app.entity.Employee;

@Repository
public interface EmployeeRepository extends MongoRepository<Employee, String> {

}

App.java
package com.sample.app;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;

import com.mongodb.MongoClient;
import com.sample.app.entity.Address;
import com.sample.app.entity.Employee;
import com.sample.app.repository.AddressRepository;
import com.sample.app.repository.EmployeeRepository;

@SpringBootApplication
public class App {
 @Value("${spring.data.mongodb.database}")
 private String database;

 @Value("${spring.data.mongodb.host}")
 private String host;

 @Value("${spring.data.mongodb.port}")
 private int port;

 @Autowired
 private EmployeeRepository empRepository;

 @Autowired
 private AddressRepository addressRepository;

 public static void main(String[] args) {

  SpringApplication.run(App.class, args);
 }

 public void dropPreviousData() {
  MongoClient mongoClient = new MongoClient(host, port);

  MongoOperations mongoOps = new MongoTemplate(mongoClient, database);

  mongoOps.dropCollection("employees");
  mongoOps.dropCollection("addresses");
 }

 @Bean
 public CommandLineRunner demo() {
  return (args) -> {

   dropPreviousData();

   Address addr1 = new Address("Bangalore", "India");
   Address addr2 = new Address("Hyderabad", "India");
   Address addr3 = new Address("Chennai", "India");

   addr1 = addressRepository.save(addr1);
   addr2 = addressRepository.save(addr2);
   addr3 = addressRepository.save(addr3);

   Employee emp1 = new Employee("Phalgun", "Garimella", addr1.getId());
   Employee emp2 = new Employee("Sankalp", "Dubey", addr2.getId());
   Employee emp3 = new Employee("Arpan", "Debroy", addr3.getId());

   empRepository.saveAll(Arrays.asList(emp1, emp2, emp3));

   List<Employee> emps = empRepository.findAll();

   for (Employee emp : emps) {
    System.out.println("************************************");
    Address addr = addressRepository.findById(emp.getAddressId()).get();
    System.out.println(emp);
    System.out.println(addr);
    System.out.println("************************************\n");
   }

  };
 }
}

Create application.properties file under src/main/resources folder.

application.properties
spring.data.mongodb.database=myorg
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost

logging.level.org.springframework.data=WARN

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>springDataMongo</groupId>
 <artifactId>springDataMongo</artifactId>
 <version>1</version>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.6.RELEASE</version>
 </parent>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-mongodb</artifactId>
  </dependency>
 </dependencies>
</project>


Total project structure looks like below.


Run App.java, you can see below messages in console.
************************************
Employee [id=5d518ce45d30d03c83bdd6c3, firstName=Phalgun, lastName=Garimella, addressId=5d518ce45d30d03c83bdd6c0]
Address [id=5d518ce45d30d03c83bdd6c0, city=Bangalore, country=India]
************************************

************************************
Employee [id=5d518ce45d30d03c83bdd6c4, firstName=Sankalp, lastName=Dubey, addressId=5d518ce45d30d03c83bdd6c1]
Address [id=5d518ce45d30d03c83bdd6c1, city=Hyderabad, country=India]
************************************

************************************
Employee [id=5d518ce45d30d03c83bdd6c5, firstName=Arpan, lastName=Debroy, addressId=5d518ce45d30d03c83bdd6c2]
Address [id=5d518ce45d30d03c83bdd6c2, city=Chennai, country=India]
************************************

You can confirm the same via mongo shell.
> db.addresses.find().pretty()
{
 "_id" : ObjectId("5d518ce45d30d03c83bdd6c0"),
 "city" : "Bangalore",
 "country" : "India",
 "_class" : "com.sample.app.entity.Address"
}
{
 "_id" : ObjectId("5d518ce45d30d03c83bdd6c1"),
 "city" : "Hyderabad",
 "country" : "India",
 "_class" : "com.sample.app.entity.Address"
}
{
 "_id" : ObjectId("5d518ce45d30d03c83bdd6c2"),
 "city" : "Chennai",
 "country" : "India",
 "_class" : "com.sample.app.entity.Address"
}
> 
> db.employees.find().pretty()
{
 "_id" : ObjectId("5d518ce45d30d03c83bdd6c3"),
 "firstName" : "Phalgun",
 "lastName" : "Garimella",
 "addressId" : "5d518ce45d30d03c83bdd6c0",
 "_class" : "com.sample.app.entity.Employee"
}
{
 "_id" : ObjectId("5d518ce45d30d03c83bdd6c4"),
 "firstName" : "Sankalp",
 "lastName" : "Dubey",
 "addressId" : "5d518ce45d30d03c83bdd6c1",
 "_class" : "com.sample.app.entity.Employee"
}
{
 "_id" : ObjectId("5d518ce45d30d03c83bdd6c5"),
 "firstName" : "Arpan",
 "lastName" : "Debroy",
 "addressId" : "5d518ce45d30d03c83bdd6c2",
 "_class" : "com.sample.app.entity.Employee"
}

You can download complete working application from this link.


Previous                                                    Next                                                    Home

No comments:

Post a Comment