尝试@DBRef的使用

两个document结构如下:

@Data
@Document(collection = "main")
public class Main {

    @Id
    private String id;

    private String name;

    private String age;

    private String gender;

    @DBRef
    private Ref ref;
}
@Data
@Document(collection = "ref")
public class Ref {

    @Id
    private String id;

    private String address;

    private String father;

    private String mother;
}

测试方法:

@Test
public void testInsert() {

    Ref ref = new Ref();
    ref.setAddress("滨江火炬大道");
    ref.setFather("zhang");
    ref.setMother("wang");
    refRepository.save(ref).subscribe();

    Main main = new Main();
    main.setName("main");
    main.setAge("18");
    main.setGender("男");
    main.setRef(ref);
    mainRepository.save(main).subscribe();
}

插入报错:

Caused by: org.springframework.data.mapping.MappingException: Cannot create a reference to an object with a NULL id.

要保证被ref的实体先于引用ref的实体生成,那么修改成如下形式(这个形式其实很不好):

数据格式:

  

测试查询主实体:

@Test
    public void getMain() {
        Mono<Main> byId = mainRepository.findById("5bed07c946ce5e02f8cd0ee9");
        Main main = byId.block();
        System.out.println("main = " + main);
    }
main = Main(id=5bed07c946ce5e02f8cd0ee9, name=main, age=18, gender=男, ref=Ref(id=5bed07c946ce5e02f8cd0ee8, address=滨江火炬大道, father=zhang, mother=wang))

DONE ~

 

update :

那么实际中写的时候遇见这么一种情况,批量操作如何实现 main等ref全部批量保存完成?

CountDownLatch countDownLatch = new CountDownLatch(1);
refService.saveAll(reflist).subscribe(null, null, countDownLatch::countDown);
countDownLatch.await(10, TimeUnit.SECONDS);
mainService.saveAll(mainlist).subscribe();