我对 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;
}