0

I'm trying to use the dbref function from spring.

My Code:

@EnableAutoConfiguration
@RestController
@RequestMapping("/poi")
public class PoiBasicController {
    @Autowired
    private PoiRepository poiRepository;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public @ResponseBody ResponseEntity<String> add(@RequestBody PointOfInterest poi) {

        poiRepository.insert(poi);

        return ResponseEntity.status(HttpStatus.OK).body(null);
    }

@EnableAutoConfiguration
@RestController
@RequestMapping("/tour")
public class TourController {

    @Autowired
    private TourRepository tourRepository;

    @Autowired
    private PoiRepository poiRepository;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public @ResponseBody ResponseEntity<String> addTour(@RequestBody Tour tour) {
        tourRepository.insert(tour);
        return ResponseEntity.status(HttpStatus.OK).body(null);
    }

@Document
public class Tour {
    @Id
    private String id;
    private HashMap<String, String> title;
    private HashMap<String, String> description;
    private List<String> images;
    @DBRef(db = "pois")
    private List<PointOfInterest> poiList;

@Document(collection = "pois")
public abstract class PointOfInterest {
    @Id
    private String id;

    private UpperCategory upperCategory;
    private List<String> tags;
    private int priority;
    private List<String> images;
    private LocationWrapper location;
    /*
        Languagekey, description
     */
    private HashMap<String, String> description;

The Poi class is implemented by different types of poi (e.g. Culture). I want to reference the pois in my Tour object as list.

I do a POST to store a poi in my pois collection.

The Problem: When I do a POST on my tour with the objectID-reference of the poi object, my poi List in tours is always null.

I understood the @DBRef right, didn't I?

Edit1: Error message

The problem is: Assume you have two pois in the database referenced with "poi_id_1" and "poi_id_2". Now I start an API call to /tour/add with the following JSON array in it (other arguments ommited):
"poiList": [{"id": "poi_id_1"}, {"id":"poi_id_2"}]

I get a 200.

BUT: When I start a query on tours, I get "poiList": [null] as result. (other arguments ommited)

Thanks for your help in advance :)

1 Answers1

0

You should not be using the db property in @DBRef as your POI's reside in the same database, and collection name is inferred from your domain object.

By specifying @DBRef(db="...") you are asking Spring Data to look up entries in a different database altogether.

Simply use @DBref

Yuriy Kovalek
  • 694
  • 5
  • 10