我是morphia的新手,爲獲得索引註釋工作而苦苦掙扎。我在靜態塊中創建數據源並在同一個塊中調用ensureIndexes,但是它無法應用索引。如果我在保存它工作的對象之前放置這條線。帶嗎啡的索引註釋不起作用
順便說一句,我使用Java的playframework 2。
public class MongoService {
static private MongoClient mongoClient = null;
static Datastore ds = null;
static {
MorphiaLoggerFactory.reset();
MorphiaLoggerFactory.registerLogger(com.google.code.morphia.logging.slf4j.SLF4JLogrImplFactory.class);
try {
Logger.debug("mongo uri:" + mongoUri);
MongoClientURI uri = new MongoClientURI(mongoUri);
mongoClient = new MongoClient(uri);
ds = new Morphia().createDatastore(mongoClient, dbname);
ds.ensureIndexes();
ds.ensureCaps();
}catch(Exception e) {
Logger.error("exception:" + e.fillInStackTrace());
}
}
public static User insertUser(User user) {
//ds.ensureIndexes(); //UNCOMMENTING THIS LINE MAKES IT WORK
ds.save(user);
return user;
}
這是用戶類的實現:
@Entity(noClassnameStored = true)
public class User {
@Id private ObjectId id;
@Indexed(value=IndexDirection.ASC, name="email", unique=true, dropDups=true)
public String email;
}
謝謝你的回答......我花了一段時間才弄清楚發生了什麼事。沿着你正在做的工作的一個更明確的解決方案是確保所有具有@Indexed註釋的類的索引是這樣的:ds.ensureIndexes(User.class,false)。最後一個參數指定索引構建是否發生在後臺。 –