【问题标题】:Spring data + MongoTemplate - constraints on document won't affect inserts\savesSpring data + MongoTemplate - 对文档的约束不会影响插入\保存
【发布时间】:2014-06-28 21:13:23
【问题描述】:

我在一个简单的 web 应用程序中使用 spring 数据。

我有一个对其中一个字段有唯一约束的简单文档:

@Document
@CompoundIndexes({ @CompoundIndex(name = "playerConstraint", def = "{ 'playerId': 1  }", unique = true)
public class InProgressGameRound extends AbstractDocument {
 //...
}

问题是当我调用该文档的存储库时: this.repository.save(newRound);

数据库中已经存在 newRound.playerId - 我没有遇到任何异常! 程序计数器继续前进,即使文档没有真正保存(由于约束),似乎一切都很好

如果我尝试手动将相同的条目插入到 mongoDB 中 - 我会收到一个错误,指出约束不允许他插入。

如何验证保存是否有效(使用存储库)?

谢谢

【问题讨论】:

  • 你解决过这个问题吗?

标签: java spring mongodb spring-data mongotemplate


【解决方案1】:

我还建议一种变体。我不确定您的数据结构,但您可以尝试插入没有“playerId”的文档。 Mongo 会为您自动为每个对象生成 _id,这是唯一的,甚至更多 _id 字段默认在 mongo 中自动索引。

【讨论】:

    猜你喜欢
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-21
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多