【发布时间】:2017-11-22 16:10:57
【问题描述】:
我正在尝试使用@DBRef 在模型中创建一个列表,但我无法让它工作。
这是我的用户模型:
@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;
}
服务器型号:
@Data
@Document
public class Server {
@Id
@JsonSerialize(using = ToStringSerializer.class)
private ObjectId id;
@NotBlank
private String name;
@NotBlank
private String host;
}
结构很简单,每个用户可以有多个服务器。但是当我向用户添加服务器时,会创建服务器,但服务器数组包含一个null 条目("servers" : [ null ])。所以服务器不会添加到用户。这就是我创建服务器并将其添加到用户的方式:
@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);
}
所以我只需创建并保存服务器,将服务器添加到用户,然后保存用户。但它不起作用。我一直有一个包含一个 null 条目的数组。
我看过这个页面:http://www.baeldung.com/cascading-with-dbref-and-lifecycle-events-in-spring-data-mongodb。但它是用于保存子文档,而不是用于链接它。它也适用于单个文档,而不适用于数组或列表。
为什么我的列表没有正确保存?
我所有的库都来自 Spring Boot 版本 2.0.0.M6。
更新
从用户的服务器属性中删除@DBRef 时,服务器会被保存,但它们当然会在server 集合和每个user.servers 中双重创建。所以错误与引用有关。
【问题讨论】:
-
你能不能把Authentication类也放上来,这样我们就可以试试我们的代码了
-
以上代码对我有用
-
@pvpkiran Authentication接口来自spring(
org.springframework.security.core.Authentication) -
@pvpkiran 当我从用户对象编辑其他属性时它工作正常,只有服务器列表不起作用。
-
你能检查
user.getServers()是否给你返回一个列表吗?
标签: spring mongodb reactive-programming spring-webflux dbref