Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java @使用命名集合时忽略索引注释_Java_Spring_Mongodb_Spring Data_Spring Data Mongodb - Fatal编程技术网

Java @使用命名集合时忽略索引注释

Java @使用命名集合时忽略索引注释,java,spring,mongodb,spring-data,spring-data-mongodb,Java,Spring,Mongodb,Spring Data,Spring Data Mongodb,我有一个pojo注释如下: @Document class Car { @Id String id ; @Indexed String manufacturer ; } 我正在使用MongoTemplate插入到mongo中。如果插入而不指定集合名称,则一切正常。但是,如果我指定一个集合名称,则除了\u id一个之外,不会创建任何索引 我确实需要能够手动指定集合名称,因为: 我需要确保Car的不同子类在同一个集合中结束 我想把每年价值的汽车单独收藏起来 我必须自己手动

我有一个pojo注释如下:

@Document
class Car {

  @Id
  String id ;

  @Indexed
  String manufacturer ;

}
我正在使用
MongoTemplate
插入到mongo中。如果插入而不指定集合名称,则一切正常。但是,如果我指定一个集合名称,则除了
\u id
一个之外,不会创建任何索引

我确实需要能够手动指定集合名称,因为:

  • 我需要确保
    Car
    的不同子类在同一个集合中结束
  • 我想把每年价值的
    汽车
    单独收藏起来

我必须自己手动调用
ensureIndex()
吗?如果是,有没有一种方法可以使用我的
@索引的
注释?我试图保存的实际对象比“Car”复杂得多

不幸的是
MongoTemplate
函数

public void insert(Object objectToSave, String collectionName)
使用
collectionName
仅用于保存对象,而不用于创建任何带注释的索引。 如果将对象传递给保存操作,则应用程序事件侦听器MongOperateSistentEntityIndexCreator
将扫描保存的实体类中的
@Indexed
注释并创建索引。但它会根据下一个公式(来源)检测集合名称:

其中,
index.collection()
是从
@index
注释和
实体.getCollection()
@Document
注释收集的

因此,您需要手动调用
ensureIndex()
。 这是一种奇怪的行为。我想你可以在这里打开bug:

编辑: 我认为您可以创建一个函数,该函数返回用
@Document
注释的所有类,还可以从
汽车中获取mongodb的所有集合。
。然后,您可以分析用
@index
注释的所有字段,并因此使用集合列表为此字段调用
ensureIndex

我确实需要能够手动指定集合名称,因为:

对于第一条语句,您可以使用
@Document
元数据注释强制执行单个集合:

@Document(collection="cars")
class Car {

    @Id
    String id ;

    @Indexed
    String manufacturer ;

}

@Document(collection="cars")
class Honda extends Car {

}

@Document(collection="cars")
class Volvo extends Car {

}

@Document
的collection字段将负责car的每个子类进入cars集合,另外,索引是在
@Indexed
注释的帮助下自动创建的。

作为应用程序启动的一部分,您最好转到数据库级别,检查集合是否有您需要的索引,并使用和调用ensureIndex

提示:在为您的应用程序配置mongo的类上实现InitializingBean,并在那里发挥神奇的作用


没有说教,伊姆霍斯普林擅长某些事情,也擅长其他事情。除了在非XA环境中进行DI&TXN管理之外,我还试图避免膨胀。

经过长时间的搜索,我认为目前无法使用注释,因此我创建了一种编程方式来管理此场景

创建普通索引和复合索引

首先,我定义了一个对象来映射索引结构

public class CollectionDefinition {

private String id;
private String collectionName;
private LinkedHashMap<String, Sort.Direction> normalIndexMap;
private ArrayList<String> compoundIndexMap;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getCollectionName() {
    return collectionName;
}

public void setCollectionName(String collectionName) {
    this.collectionName = collectionName;
}

public LinkedHashMap<String, Sort.Direction> getNormalIndexMap() {
    return normalIndexMap;
}

public void setNormalIndexMap(LinkedHashMap<String, Sort.Direction> normalIndexMap) {
    this.normalIndexMap = normalIndexMap;
}

public ArrayList<String> getCompoundIndexMap() {
    return compoundIndexMap;
}

public void setCompoundIndexMap(ArrayList<String> compoundIndexMap) {
    this.compoundIndexMap = compoundIndexMap;
}
然后我们可以创建集合和索引

private List<IndexDefinition> createIndexList(Map<String, Sort.Direction> normalIndexMap) {
    Set<String> keySet = normalIndexMap.keySet();
    List<IndexDefinition> indexArray = new ArrayList<>();
    for (String key : keySet) {
        indexArray.add(new Index(key, normalIndexMap.get(key)).background());
    }
    return indexArray;
}
私有列表createIndexList(映射normalIndexMap){
Set keySet=normalIndexMap.keySet();
List indexArray=new ArrayList();
用于(字符串键:键集){
add(新索引(key,normalIndexMap.get(key)).background());
}
返回指数;
}
生成的单索引列表可用于创建单字段索引

private void createIndexes(List<IndexDefinition> indexDefinitionList, MongoOperations mongoOperations, String collectionName) {
    indexDefinitionList.forEach(indexDefinition -> mongoOperations.indexOps(collectionName).ensureIndex(indexDefinition));
}
private void createIndexes(列表索引定义列表、MongoOperations MongoOperations、字符串集合名称){
indexDefinitionList.forEach(indexDefinition->mongoOperations.indexOps(collectionName).ensureIndex(indexDefinition));
}
复合索引或多字段索引比较复杂,我们需要创建DBObjects来定义索引

private List<DBObject> createCompountIndexList(List<String> compoundIndexStringMapList) {//NOSONAR IS IN USE
    if (compoundIndexStringMapList == null || compoundIndexStringMapList.isEmpty())
        return new ArrayList<>(); //NOSONAR
    ObjectMapper mapper = new ObjectMapper();
    List<DBObject> basicDBObjectList = new ArrayList<>();
    for (String stringMapList : compoundIndexStringMapList) {
        LinkedHashMap<String, Integer> parsedMap;
        try {
            parsedMap = mapper.readValue(stringMapList, new TypeReference<Map<String, Integer>>() {
            });
            BasicDBObjectBuilder dbObjectBuilder = BasicDBObjectBuilder.start();
            Iterator it = parsedMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry indexElement = (Map.Entry) it.next();
                dbObjectBuilder.add((String) indexElement.getKey(), indexElement.getValue());
                it.remove(); // avoids a ConcurrentModificationException
            }
            basicDBObjectList.add(dbObjectBuilder.get());
        } catch (IOException e) {//NOSONAR I´m logging it, we can not do anything more here cause it is part of the db configuration settings that need to be correct
            Logger.getLogger(JsonCollectionCreation.class).error("The compound index definition " + stringMapList + " is not correct it can not be mapped to LinkHashMap");
        }

    }
    return basicDBObjectList;
}
private List createComponentIndexList(List componendexStringMapList){//NOSONAR正在使用中
if(compoundexstringmaplist==null | | compoundexstringmaplist.isEmpty())
返回新的ArrayList();//NOSONAR
ObjectMapper mapper=新的ObjectMapper();
List basicDBObjectList=新建ArrayList();
用于(字符串字符串字符串映射列表:compoundIndexStringMapList){
LinkedHashMap-parsedMap;
试一试{
parsedMap=mapper.readValue(stringMapList,新类型引用(){
});
BasicDBObjectBuilder dbObjectBuilder=BasicDBObjectBuilder.start();
迭代器it=parsedMap.entrySet().Iterator();
while(it.hasNext()){
Map.Entry indexElement=(Map.Entry)it.next();
添加((字符串)indexElement.getKey(),indexElement.getValue());
it.remove();//避免ConcurrentModificationException
}
添加(dbObjectBuilder.get());
}catch(IOException e){//NOSONAR我正在记录它,我们不能在这里做更多的事情,因为它是数据库配置设置的一部分,需要正确
Logger.getLogger(JsonCollectionCreation.class).error(“复合索引定义“+stringMapList+”不正确,无法映射到LinkHashMap”);
}
}
返回基本对象列表;
}
结果可用于在集合中创建索引

private void createCompoundIndex(List<DBObject> compoundIndexList, MongoOperations mongoOperations, String collectionName) {
    if (compoundIndexList.isEmpty()) return;
    for (DBObject compoundIndexDefinition : compoundIndexList) {
        mongoOperations.indexOps(collectionName).ensureIndex(new CompoundIndexDefinition(compoundIndexDefinition).background());
    }
}
private void createCompoundIndex(列表compoundIndexList、MongoOperations、MongoOperations、String collectionName){
if(compoundexlist.isEmpty())返回;
for(DBObject compoundexdefinition:compoundexlist){
mongoOperations.indexOps(collectionName).ensureIndex(新的CompoundIndexDefinition(CompoundIndexDefinition.background());
}
}

那没关系,除非,正如你所说,这对我的第二点没有帮助=(我不理解你的第二点。请给出一个例子。不确定这个用例有多广泛,但对我来说,为min的每个客户维护完全独立的集合是很有意义的
private void createIndexes(List<IndexDefinition> indexDefinitionList, MongoOperations mongoOperations, String collectionName) {
    indexDefinitionList.forEach(indexDefinition -> mongoOperations.indexOps(collectionName).ensureIndex(indexDefinition));
}
private List<DBObject> createCompountIndexList(List<String> compoundIndexStringMapList) {//NOSONAR IS IN USE
    if (compoundIndexStringMapList == null || compoundIndexStringMapList.isEmpty())
        return new ArrayList<>(); //NOSONAR
    ObjectMapper mapper = new ObjectMapper();
    List<DBObject> basicDBObjectList = new ArrayList<>();
    for (String stringMapList : compoundIndexStringMapList) {
        LinkedHashMap<String, Integer> parsedMap;
        try {
            parsedMap = mapper.readValue(stringMapList, new TypeReference<Map<String, Integer>>() {
            });
            BasicDBObjectBuilder dbObjectBuilder = BasicDBObjectBuilder.start();
            Iterator it = parsedMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry indexElement = (Map.Entry) it.next();
                dbObjectBuilder.add((String) indexElement.getKey(), indexElement.getValue());
                it.remove(); // avoids a ConcurrentModificationException
            }
            basicDBObjectList.add(dbObjectBuilder.get());
        } catch (IOException e) {//NOSONAR I´m logging it, we can not do anything more here cause it is part of the db configuration settings that need to be correct
            Logger.getLogger(JsonCollectionCreation.class).error("The compound index definition " + stringMapList + " is not correct it can not be mapped to LinkHashMap");
        }

    }
    return basicDBObjectList;
}
private void createCompoundIndex(List<DBObject> compoundIndexList, MongoOperations mongoOperations, String collectionName) {
    if (compoundIndexList.isEmpty()) return;
    for (DBObject compoundIndexDefinition : compoundIndexList) {
        mongoOperations.indexOps(collectionName).ensureIndex(new CompoundIndexDefinition(compoundIndexDefinition).background());
    }
}