在不同收藏中的子女文件中独立定义同一领域的索引



我有两个看起来像这样的类:

@Document(collection = 'rule')
class Rule {
    @Indexed(unique = true)
    String name
}
@Document(collection = 'archived_rule')
class ArchivedRule extends Rule {
    @Indexed(unique = false)
    String name
}

规则是我的应用程序使用的主要域类。每个规则的最新版本仅存储在"规则"集合中。更新规则后,将制作其副本并保存在" Archived_rule"集合中。

名称字段在"规则"集合中应是唯一的。它应该能够在" Archived_rule"集合中具有重复。

定义我的课程,因为上述我的课程似乎不起作用。当我启动应用程序时,我会得到这样的例外:

Caused by: org.springframework.data.mapping.model.MappingException: Ambiguous field mapping detected! Both @org.springframework.data.mongodb.core.index.Indexed(expireAfterSeconds=-1, dropDups=false, sparse=false, useGeneratedName=false, background=false, unique=true, name=, collection=, direction=ASCENDING) private java.lang.String ...Rule.name and @org.springframework.data.mongodb.core.index.Indexed(expireAfterSeconds=-1, dropDups=false, sparse=false, useGeneratedName=false, background=false, unique=false, name=, collection=, direction=ASCENDING) private java.lang.String ...ArchivedRule.name map to the same field name name! Disambiguate using @Field annotation!

我也尝试过在存档类中完全没有指定名称字段,但是在这种情况下,它在" Archived_rule"集合中的"名称"字段上创建了唯一的索引。

我以为我可以通过继承而制作规则和存档无关,然后明确重新定义我需要从ArchivedRule中的规则中保存的所有字段。不过,我想避免这样做。

是否有其他方法可以指定我的类,以便该规则。名称具有唯一的索引和归档。名称没有唯一的索引?

我能够通过添加一个带有共享字段的抽象基类来解决此问题,而这些字段均以规则和存档延伸。然后,他们每个人都使用适当的索引配置定义自己的名称版本。

class RuleBase {
    String sharedField
}
@Document(collection = 'rule')
class Rule extends RuleBase {
    @Indexed(unique = true)
    String name
}
@Document(collection = 'archived_rule')
class ArchivedRule extends RuleBase {
    @Indexed(unique = false)
    String name
}

最新更新