Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data mongodb @DBRef list

I am trying to have a list in a model using @DBRef but I can't get it to work. This is my User model:

@Data
@Document
public class User {

    @Id
    @JsonSerialize(using = ToStringSerializer.class)
    private ObjectId id;

    @Indexed(unique = true)
    @NotBlank
    private String email;

    @NotBlank
    private String name;

    @NotBlank
    private String password;

    @DBRef
    private List<Server> servers;
}

Server model:

@Data
@Document
public class Server {

    @Id
    @JsonSerialize(using = ToStringSerializer.class)
    private ObjectId id;

    @NotBlank
    private String name;

    @NotBlank
    private String host;
}

The structure is very simple, every user can have multiple servers. But when I add servers to the user the server is created, but the servers array contains one null entry("servers" : [ null ]). So the server isn't added to the user. This is how I create a server and add it to an user:

@PostMapping
public Mono create(@Valid @RequestBody Server server, Mono<Authentication> authentication) {
    return this.serverRepository.save(server).then(authentication.flatMap(value -> {
        User user = (User) value.getDetails();
        user.getServers().add(server);

        return userRepository.save(user);
    })).map(value -> server);
}

So I simply create and save a server, add the server the user and then save the user. But it doesn't work. I keep having an array with one null entry.

I've seen this page: http://www.baeldung.com/cascading-with-dbref-and-lifecycle-events-in-spring-data-mongodb. But it is for saving the child document, not for linking it. Also it is for a single document, not for an array or list.

Why is my list not being saved correctly?

All my libraries are coming from spring boot version 2.0.0.M6.

UPDATE When removing @DBRef from the user's servers property the servers are getting saved, but they of course get double created, in the server collection and in every user.servers. So the error has something to do with references.

like image 497
Jan Wytze Avatar asked Sep 18 '26 21:09

Jan Wytze


1 Answers

After some googling I found the answer...
https://jira.spring.io/browse/DATAMONGO-1583
https://jira.spring.io/browse/DATAMONGO-1584

Reactive mongo doesn't support this.

like image 82
Jan Wytze Avatar answered Sep 21 '26 14:09

Jan Wytze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!