问题描述
我有一个人实体,由音乐家和政客继承,还有一个存储库PersonRepository.
I have a entity Person, inherited by Musician and Politician and a repository PersonRepository.
我试图使用PersonRepository.save(..)默认方法将所有三个实体保存到MongoDB的一个集合人"中,但是不知何故,Spring-Data-MongoDB将其保存到3个单独的集合人",音乐家"和政客".
I am trying to have all three entities saved into the a collection "person" in MongoDB using PersonRepository.save(..) default method but somehow, Spring-Data-MongoDB save it into 3 separate collections "person", "musician" and "politician".
Java代码:
@Document
public class Person {
@Id private String id;
@Indexed private String name;
@TextIndexed private String biography;
}
@Document
public Musician extends Person {
private String something;
}
@Document
public Politician extends Person {
private String somethingElse;
}
@Repository
public interface PersonRepository extends CrudRepository<User, String> {
}
在阅读了一些帖子之后,我必须将所有三个实体的集合名称设置为批注@Document(collection ="person"),以便存储库将其保存到同一集合中.
After reading some posts saying I have to set the collection name into the annotation @Document(collection = "person") for all three of the entity for the repository to save it into a same collection.
它工作正常,但是当我在MongoDB中检查索引时,我不知何故得到了以保存的最后一个实体类命名的TextIndex.
It works well but when I check the Indexes in MongoDB, somehow I get the TextIndex being named after the last entity class which is saved.
似乎TextIndex总是以保存的实体类名称命名,而不是我在文档注释中设置的集合名称.
It seems that TextIndex will always being named after the entity class name being saved, and not the collection name which I have set in the document annotation.
MongoDB Shell:
db.person.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.person"
},
{
"v" : 1,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "Musician_TextIndex",
"ns" : "test.person",
"weights" : {
"description" : 1,
"name" : 10
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 3
}
]
有什么方法可以设置TextIndex名称,而不用在要保存的实体类后面命名.试图搜索可以找到任何东西.
Is there any way I could set the TextIndex name instead of naming it after the entity class which I am saving. Tried to search could find any.
推荐答案
当前无法使用基于注释的设置来设置TextIndex
的索引名称.为此,请通过template
使用IndexOperations
手动设置文本索引.
Currently there is no way of setting the index name for TextIndex
using the annotation based setup. To do so please use the IndexOperations
via the template
to set up the text index manually.
template.indexOps(Person.class)
.ensureIndex(
new TextIndexDefinitionBuilder()
.named("YourIndexNameHere")
.onField("biography")
.build());
这篇关于如何使用Spring-Data-MongoDB在实体中设置@TextIndex名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!