Reputation: 2269
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;
}
Upvotes: 2
Views: 4424
Reputation: 11
I solved the problem by this form:
public void create(Producto p) {
Morphia m =new Morphia();
Datastore ds = m.mapPackage("ec.edu.espe.as.model.Producto").createDatastore(new MongoClient(), "productoPrueba");
DBObject dbo = m.toDBObject(p);
ds.ensureIndexes();
ds.getCollection(Producto.class).insert(dbo);
}
I mean, make the ensureIndexes just before insert
Upvotes: 0
Reputation: 1514
Although for OP this wasn't the issue, I found that even though the @Entity class decorator is optional, if it's left out then field-level indexes don't get created by Morphia.
Upvotes: 0
Reputation: 11
This is my code in Play, and it works. Please try:
modelClass = Class.forName(model, true, app.classloader());
morphia.map(modelClass);
Upvotes: 1
Reputation: 2269
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);
.
.
.
Upvotes: 4
Reputation: 10859
You need to map your entity classes - either by package or by class:
ds = new Morphia().mapPackage("com.test.entities").createDatastore(mongoClient, dbname);
Upvotes: 4