0

I am trying to insert an array of json objects into mongodb. I pass the array with a POST request, using Spring

My object

@Document(collection = "Users")
public class User {
  private String name;
  private String number;
//constructors, getters, setters
}

My spring controller

@RestController
public class UserController {

  @RequestMapping(value="/postUser", method = RequestMethod.POST)
  public void postUser(@RequestBody BasicDBList users){
    ApplicationContext ctx =
      new AnnotationConfigApplicationContext(SpringMongoConfig.class);
    MongoOperations mongoOperation =
      (MongoOperations) ctx.getBean("mongoTemplate");
    mongoOperation.insert(users);
  }
}

This is my json

[
    {
        "name" : "a",
        "number" : "1"
    },
    {
        "name" : "c",
        "number" : "3"      
    }
]

What I get in return is

{
    "timestamp": 1499161260902,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "org.springframework.dao.InvalidDataAccessApiUsageException",
    "message": "No Persistent Entity information found for the class com.mongodb.BasicDBList",
    "path": "/postUser"
}

There is no problem if I do

public void postUser(@RequestBody User users)

and insert a single user. Why doesn't it work?

Evgenii
  • 389
  • 3
  • 7
  • 21

2 Answers2

0

When you add @RequestBody before the parameter, HttpMessageConvertor will try to convert json string to the specified type - BasicDBList. The json string may not match BasicDBList, so the conversion failed. You can use this:

public void postUser(@RequestBody List<User> users)
Dave Pateral
  • 1,415
  • 1
  • 14
  • 21
  • Did not help. New error is `com.mongodb.BasicDBObject cannot be cast to com.mongodb.BasicDBList` – Evgenii Jul 04 '17 at 10:14
  • Correction. I had to also change `mongoOperation.insert(users)` to `insertAll(users)`. Now it works. – Evgenii Jul 04 '17 at 10:17
0

Actually, Spring data cannot determine the collection name to save BasicDBList.
This is not related to HttpMessageConverter
You can check more here: Insert DBObject into MongoDB using Spring Data

Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: No Persitent Entity information found for the class com.mongodb.BasicDBObject at org.springframework.data.mongodb.core.MongoTemplate.determineCollectionName(MongoTemplate.java:1747)
Nttrungit90
  • 68
  • 1
  • 9