I'm pretty new to morphia and struggling with getting the index annotation to work. I'm creating the datasource in a static block and calling ensureIndexes in the same block, but it fails to apply the indexes. If I put the line right before I save the object it works.
By the way,I'm using playframework 2 with Java.
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;
}
This is the implementation of the user class:
@Entity(noClassnameStored = true)
public class User {
@Id private ObjectId id;
@Indexed(value=IndexDirection.ASC, name="email", unique=true, dropDups=true)
public String email;
}
There seems to be a conflict between package loader that Morphia is using and the one that play framework is trying to use, I could not find the exact problem but as a workaround I am mapping each object one by one and that seems to be working
morph.map(User.class);
morph.map(Address.class);
.
.
.