【问题标题】:Spring JPA mongodb using annotationsSpring JPA mongodb 使用注释
【发布时间】:2013-06-09 18:32:50
【问题描述】:

帮助我理解这一点。我正在使用没有休眠或任何其他 jpa 提供程序的 spring-data-mongodb。我的领域模型是这样的:

public class User {
  @Id
  private String id;
  private String username;
  private String password;
  ...
}

我运行一个测试类来填充我的 mongodb 中的一些用户,它工作正常。但如果我再添加一些这样的注释:

public class User {
  @Id
  private String id;
  @Field(value="uname") private String username;
  @Field(value="pass")private String password;
  ...
}

我的测试类只添加了一个用户,下一个会抛出异常,抱怨重复条目 -

org.springframework.dao.DuplicateKeyException: E11000 重复键错误索引:gldata.user.$username_-1 dup key: { : null };嵌套异常是 com.mongodb.MongoException$DuplicateKey: E11000 duplicate key error index: gldata.user.$username_-1 dup key: { : null }

我在这里错过了什么?

【问题讨论】:

  • 我的猜测是,在第二种情况下,Spring-JPA 无法自动生成 id,第一个 id(mongo 中的对象 id)使用 null 生成,第二个 id 然后变成复制。但为什么呢?

标签: spring mongodb annotations persistence


【解决方案1】:

虽然我不知道为什么会发生这种情况,但我找到了解决方法。 id 字段使用 ObjectId 而不是 String,效果很好。

【讨论】:

    猜你喜欢
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 2011-12-07
    相关资源
    最近更新 更多