Id bug in where criteria - Spring Data MongoDB 1.0.0.M2
After refactoring my tutorial from http://krams915.blogspot.com/2011/02...-tutorial.html so that the domain class uses @Document and @Id, I was able to remove references to a custom "pid" property as the primary id. I can now directly use "id" as the primary id.
However there's a new problem when performing an update.
The following block of code fails:
Code:
// Find an entry where id matches the id
Query query = new Query(where("id").is(person.getId()));
// Declare an Update object.
// This matches the update modifiers available in MongoDB
Update update = new Update();
logger.debug("Person's name: " + person.getFirstName());
update.set("firstName", person.getFirstName());
mongoTemplate.updateMulti(query, update);
update.set("lastName", person.getLastName());
mongoTemplate.updateMulti(query, update);
update.set("money", person.getMoney());
mongoTemplate.updateMulti(query, update);
The reason why it fails is because there's no "id" field in the MongoDB database. If I call db.mycollection.find() I get the following:
Code:
)
{ "_id" : "c72c1e41-6cd4-446a-95e8-5a76c3492c9a", "firstName" : "John", "lastName" : "Smith", "money" : 1000 }
{ "_id" : "ef283bfd-8dec-4fde-a7d6-58acb27dac36", "firstName" : "Jane", "lastName" : "Adams", "money" : 2000 }
To resolve the issue, I had to modify the where clause to:
Code:
Query query = new Query(where("_id").is(person.getId()));
I changed "id" to "_id". However, if that's the case, the other queries for delete, get, and getAll should follow. But they don't. They work as expected even regardless if they're using "id" or "_id" in the query. Only the update fails when using "id".
Here's the code for the get, getAll, and delete methods. Note, you can interchange the "id" and "_id" here without any problems.
Code:
/**
* Retrieves all persons
*/
public List<Person> getAll() {
logger.debug("Retrieving all persons");
// Find an entry where id property exists
Query query = new Query(where("id").exists(true));
// Execute the query and find all matching entries
List<Person> persons = mongoTemplate.find(query, Person.class);
return persons;
}
/**
* Retrieves a single person
*/
public Person get( String id ) {
logger.debug("Retrieving an existing person");
// Find an entry where id matches the id
Query query = new Query(where("id").is(id));
// Execute the query and find one matching entry
Person person = mongoTemplate.findOne("mycollection", query, Person.class);
return person;
}
/**
* Deletes an existing person
*/
public Boolean delete(String id) {
logger.debug("Deleting existing person");
try {
// Find an entry where id matches the id
Query query = new Query(where("id").is(id));
// Run the query and delete the entry
mongoTemplate.remove(query);
return true;
} catch (Exception e) {
logger.error("An error has occurred while trying to delete new user", e);
return false;
}
}