0

I am developing Spring Boot MongoDB example using V2.4.5. In this example when I am doing repository query, Long fields values are not getting mapped. Sample document value from 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);
    }
}

PurchaseOrderServiceImpl.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);
    }

}

PurchaseOrder.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;
}

Output I am getting is

{
    "_id" : ObjectId("60a536412306ab5bdd7a6b06"),
    "user" : {
        "id" : null,
        "firstname" : "vins",
        "lastname" : "guru",
        "email" : "[email protected]"
    },
    "product" : {
        "id" : null,
        "description" : "ipad"
    },
    "price" : 300
}

PurchaseRepository.java

public interface PurchaseOrderRepository extends MongoRepository<PurchaseOrder, String> {
    @Query("{ 'user.id': ?0 }")
    List<PurchaseOrder> findByUserId(Long userId);
}

enter image description here

8
  • just curious, have you tried with integers? Or can u tell me what is the data type that saved in db?
    – varman
    May 19, 2021 at 16:50
  • double check your database, the id is ObjectId or Long? (int32/ int64). This measn, you try to convert ObjectId to Long
    – varman
    May 19, 2021 at 16:54
  • And pls post the repository too
    – varman
    May 19, 2021 at 16:55
  • I noticed some problems, you defined Long as id in purchesedOrder. But it was saved as ObjectId in db. So better you can make it as private ObjectId _id;, elese you can write custom converters or you can even you setters to set values to id. If you gonna use ObjectId, then change string to MongoRepository<PurchaseOrder, ObjectId>. You don't need even @Query, you can use, findByUser_id(Long id) . Underscore (_) used for go inside the objects. And its readable
    – varman
    May 19, 2021 at 17:09
  • Since you are using spring boot and its handling dependancy injection, PurchaseOrderService interface is redundant, you may remove it, you can inject the service class in controller directly.
    – varman
    May 19, 2021 at 17:14

1 Answer 1

2

The reason why you get null, Mongodb default field of id is _id. And spring data converts id to _id in any classes. When you try to run, you can check the console find using query: { "user._id" : 1} fields: Document{{}}. It mentioned _id there also which is not mapped to database, database has id. (No underscore). To over come this problem ,you can use @Field.

public class User {
    @Field("id")
    private Long id;
    private String firstname;
    private String lastname;
    private String email;
}

Or you can use _id everywhere(In classes and collections)

8
  • Thanks for detailed response, still code is not working well, could you please try ? I have posted all code
    – Prateek
    May 19, 2021 at 17:53
  • I have tried wht you gave and checked (not git). I will check git code also. Give me some time
    – varman
    May 19, 2021 at 17:53
  • I haven't installed gradle, im using maven, with your code, its working fine for me. Postman img ibb.co/60tSPr7 . Check you have added @Field("id") in user
    – varman
    May 19, 2021 at 18:06
  • Noticed in the git @Query("{ 'user.userId': ?0 }") should be @Query("{ 'user.id': ?0 }")
    – varman
    May 19, 2021 at 18:08
  • 1
    Thanks, its working now only getting "_id": { "timestamp": 1621440065, "date": 1621440065000 }, for _id field
    – Prateek
    May 19, 2021 at 18:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.