3

I have created a project using AngularJS + Spring-data-mongodb + MongoDb. I'd like to manage CRUD operations with a model that change dynamically according to the concept of object inheritance.

The frontend: If user selects a "vehicle" then the form will contain only attributes of vehicle. If user selects a vehicle type "car" then the form will contain the attributes of "vehicle" plus the attributes of "car". If user selects a vehicle type "motorcycle" then the form will contain the attributes of "vehicle" plus the attributes of "motorcycle".

AngularJS form model:

<div ng-controller="vehicleFormCtrl">

  <input type="text" class="form-control" id="InputFieldA" ng-model="vehicle.name">

  <select class="form-control" ng-model="vehicleType" ng-change="selectVehicleType()" ng-options="k as v for (k, v) in vehicleTypes">
  </select>

  ...
  <input type="text" class="form-control" id="InputFieldCar" ng-model="car.name">

  ...
  <input type="text" class="form-control" id="InputFieldMotorcyle" ng-model="motorcycle.name">
   ...
</div>

Java object:

@Document
public class Vehicle {

    @Id
    private String id;
    ...
    private String type;
    private String name;

}

@Document
public class Car extends Vehicle {

    @Id
    private String id;
    ...
    private String carColor;
}

@Document
public class Motorcycle extends Vehicle {

    @Id
    private String id;
    ...
    private String motorcycleColor;
}

This is the Spring Controller method:

@RequestMapping(method = RequestMethod.POST, value = "/save", consumes = "application/json",produces = "application/json")
@ResponseBody
public ResponseEntity<Void> saveVehicle(@RequestBody VehicleDto vehicle) {
    ...
}

This is the Spring Repository method:

MongoTemplate mongoTemplate;

Vehicle vehicle = new Vehicle();
...
mongoTemplate.insert(vehicle, "vehicle"); // Vehicle.class or Car.class or Motorcycle.class ?

Example of mongodb documents ("vehicle" collection):

{"_id":"1", "type":"Vehicle", "name":"Tesla"}
{"_id":"2", "type":"Car", "name":"LandRover", "carColor":"red"}
{"_id":"3", "type":"Motorcycle", "name":"Ducati", "motorcycleColor":"yellow"}

How can I model the @Document Pojo, CRUD methods and my AngularJs project in order to manage object inheritance? Is this approach a good choise? Which are the alternatives?

I read the mongodb documentation and other related questions like Spring-data mongodb repository and inheritance and inheritance in document database?.

I'm using AngularJS 1.2, Spring 4.1 and spring-data-mongodb 1.8. Thanks.

Community
  • 1
  • 1
j_hen
  • 173
  • 1
  • 8

0 Answers0