1. 程式人生 > 其它 >MongoTemplate如何從實體類中獲取collectionName資料庫集合名

MongoTemplate如何從實體類中獲取collectionName資料庫集合名

在按照 springboot整合mongodb 寫好一個基礎的 MongoTemplate 使用示例之後,我很好奇資料到底寫到 MongoDB 的哪個“集合” 中?

比如,我們在我們專案中呼叫 findAll 方法來查詢 MongoDB 中的資料:

public List<Student> findAll() {
    return mongoTemplate.findAll(Student.class);
}

而跟蹤一下 MongoTemplate#findAll 的原始碼:

MongoTemplate&#35;getCollectionName 獲取集合名稱的原始碼:

成員變數 operations 是型別為 EntityOperations 的例項物件。EntityOperations#determineCollectionName 的原始碼:

這邊有兩個問題:

  1. getRequiredPersistentEntity 返回的物件是什麼型別;
  2. 該型別的 getCollection 返回的值是怎麼建立的?

上面這兩個問題的答案都在 org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity 的建構函式中。

BasicMongoPersistentEntity

建構函式原始碼如下:

public BasicMongoPersistentEntity(TypeInformation<T> typeInformation) {
  super(typeInformation, MongoPersistentPropertyComparator.INSTANCE);
  Class<?> rawType = typeInformation.getType();
  String fallback = MongoCollectionUtils.getPreferredCollectionName(rawType); // 根據實體類型別生成“集合”名稱
  if (this.isAnnotationPresent(Document.class)) {
    Document document = this.getRequiredAnnotation(Document.class);
    this.collection = StringUtils.hasText(document.collection()) ? document.collection() : fallback;
    this.language = StringUtils.hasText(document.language()) ? document.language() : "";
    this.expression = detectExpression(document.collection());
    this.collation = document.collation();
    this.collationExpression = detectExpression(document.collation());
  } else {
    this.collection = fallback;
    this.language = "";
    this.expression = null;
    this.collation = null;
    this.collationExpression = null;
  }
  this.shardKey = detectShardKey();
}

@Document指定collection

根據上面的註解,如果實體類包含 @Document 註解,且指定了 collection 屬性:

import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.List;

@Data
@Document(collection = "t_student")
public class Student{

    private String id;
    private String name;
    private Integer age;
    private Integer sex;
    private Integer height;
    private List<Hobby> hobbies;

}

比如上述程式碼這樣寫,那麼集合名稱取值為 t_student

預設collection命名規則——實體類名+首字母小寫

如果沒有特別指定,那麼就會用 MongoCollectionUtils.getPreferredCollectionName(rawType) 返回的字串:

首先 getSimpleName,那麼原來實體類 org.coderead.entity.Student 將返回字串 Student

org.springframework.util.StringUtils#uncapitalize 作用就是首字母小寫