【问题标题】:InvalidDataAccessApiUsageException: No Persistent Entity information found for the class com.mongodb.BasicDBListInvalidDataAccessApiUsageException:找不到类 com.mongodb.BasicDBList 的持久实体信息
【发布时间】:2017-07-04 09:46:53
【问题描述】:

我正在尝试将一组 json 对象插入 mongodb。我通过POST 请求传递数组,使用Spring

我的对象

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

我的弹簧控制器

@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);
  }
}

这是我的json

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

我得到的回报是

{
    "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"
}

如果我这样做没有问题

public void postUser(@RequestBody User users)

并插入一个用户。为什么它不起作用?

【问题讨论】:

    标签: java json spring mongodb rest


    【解决方案1】:

    当你在参数前添加@RequestBody时,HttpMessageConvertor会尝试将json字符串转换为指定的类型——BasicDBList。 json字符串可能与BasicDBList不匹配,所以转换失败。你可以使用这个:

    public void postUser(@RequestBody List<User> users)
    

    【讨论】:

    • 没有帮助。新错误是com.mongodb.BasicDBObject cannot be cast to com.mongodb.BasicDBList
    • 更正。我还必须将mongoOperation.insert(users) 更改为insertAll(users)。现在可以了。
    【解决方案2】:

    其实Spring数据无法确定保存BasicDBList的集合名。
    这与 HttpMessageConverter 无关
    您可以在此处查看更多信息: 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-27
      • 1970-01-01
      • 2021-03-24
      • 2020-02-13
      • 1970-01-01
      • 2018-04-07
      • 1970-01-01
      • 2020-11-09
      相关资源
      最近更新 更多