本文介绍了Spring Data MongoDB-在使用存储库查询的响应中,长值为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用V2.4.5
开发Spring Boot MongoDB
示例。在本例中,当我执行存储库查询时,没有映射长字段值。来自MongoDB的文档值示例。
{
"_id" : ObjectId("60a536412306ab5bdd7a6b06"),
"user" : {
"id" : 1,
"firstname" : "vins",
"lastname" : "guru",
"email" : "[email protected]"
},
"product" : {
"id" : 1,
"description" : "ipad"
},
"price" : 300
}
OrderController.java
@RestController
@RequestMapping("/order-service")
public class OrderController {
@Autowired
private PurchaseOrderService purchaseOrderService;
@GetMapping("/all")
public List<PurchaseOrder> getAllOrders() {
return this.purchaseOrderService.getPurchaseOrders();
}
@PostMapping("/create")
public void createOrder(@RequestBody PurchaseOrder purchaseOrder) {
this.purchaseOrderService.createPurchaseOrder(purchaseOrder);
}
}
Purche eOrderServiceImpl.java
@Service
public class PurchaseOrderServiceImpl implements PurchaseOrderService {
@Autowired
private PurchaseOrderRepository purchaseOrderRepository;
@Override
public List<PurchaseOrder> getPurchaseOrders() {
return this.purchaseOrderRepository.findAll();
}
@Override
public void createPurchaseOrder(PurchaseOrder purchaseOrder) {
this.purchaseOrderRepository.save(purchaseOrder);
}
}
PurcheseOrder.java
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
@Document(collection = "purchase_order")
public class PurchaseOrder {
@Id
private Long id;
private User user;
private Product product;
private double price;
}
User.java
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class User {
private Long id;
private String firstname;
private String lastname;
private String email;
}
Product.java
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class Product {
private Long id;
private String description;
}
我得到的输出是
{
"_id" : ObjectId("60a536412306ab5bdd7a6b06"),
"user" : {
"id" : null,
"firstname" : "vins",
"lastname" : "guru",
"email" : "[email protected]"
},
"product" : {
"id" : null,
"description" : "ipad"
},
"price" : 300
}
Purche eRepository.Java
public interface PurchaseOrderRepository extends MongoRepository<PurchaseOrder, String> {
@Query("{ 'user.id': ?0 }")
List<PurchaseOrder> findByUserId(Long userId);
}
推荐答案
为什么会得到空,mongodb默认的id字段是_id
。而在任何类中,Spring data都会将id转换为_id
。当您尝试运行时,可以查看控制台find using query: { "user._id" : 1} fields: Document{{}}
。它也提到了_id
,没有映射到数据库,数据库有id
。(不带下划线)。要克服此问题,您可以使用@Field
。
public class User {
@Field("id")
private Long id;
private String firstname;
private String lastname;
private String email;
}
或者您可以在任何地方(在类和集合中)使用_id
这篇关于Spring Data MongoDB-在使用存储库查询的响应中,长值为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!